file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.7.0; /** * @title G-Uniswap V3 ERC20 Wrapper. * @dev G-Uniswap V3 Wrapper to deposit and withdraw. */ import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { TokenInterface } from "../../common/interfaces.sol"; import { IGUniPool, IERC20 } from "./interface.sol"; import { Helpers } from "./helpers.sol"; import { Events } from "./events.sol"; abstract contract UniswapV3Resolver is Events, Helpers { using SafeERC20 for IERC20; /** * @dev Deposit Liquidity. * @notice Deposit Liquidity to Gelato Uniswap V3 pool. * @param pool The address of pool. * @param amt0Max Amount0 Max amount * @param amt1Max Amount1 Max amount * @param slippage use to calculate minimum deposit. 100% = 1e18 * @param getIds Array of IDs to retrieve amounts. * @param setId ID stores the amount of pools tokens received. */ function deposit( address pool, uint256 amt0Max, uint256 amt1Max, uint slippage, uint256[] calldata getIds, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { amt0Max = getUint(getIds[0], amt0Max); amt1Max = getUint(getIds[1], amt1Max); Deposit memory depositData; depositData.poolContract = IGUniPool(pool); (depositData.amount0In, depositData.amount1In, depositData.mintAmount) = depositData.poolContract.getMintAmounts(amt0Max, amt1Max); uint amt0Min = wmul(amt0Max, slippage); uint amt1Min = wmul(amt1Max, slippage); require( depositData.amount0In >= amt0Min && depositData.amount1In >= amt1Min, "below min amounts" ); if (depositData.amount0In > 0) { IERC20 _token0 = depositData.poolContract.token0(); convertEthToWeth(address(_token0) == wethAddr, TokenInterface(address(_token0)), depositData.amount0In); approve(TokenInterface(address(_token0)), address(pool), depositData.amount0In); } if (depositData.amount1In > 0) { IERC20 _token1 = depositData.poolContract.token1(); convertEthToWeth(address(_token1) == wethAddr, TokenInterface(address(_token1)), depositData.amount1In); approve(TokenInterface(address(_token1)), address(pool), depositData.amount1In); } (uint amount0, uint amount1,) = depositData.poolContract.mint(depositData.mintAmount, address(this)); require( amount0 == depositData.amount0In && amount1 == depositData.amount1In, "unexpected amounts deposited"); setUint(setId, depositData.mintAmount); _eventName = "LogDepositLiquidity(address,uint256,uint256,uint256,uint256[],uint256)"; _eventParam = abi.encode(pool, amount0, amount1, depositData.mintAmount, getIds, setId); } /** * @dev Withdraw Liquidity. * @notice Withdraw Liquidity from Gelato Uniswap V3 pool. * @param pool The address of pool. * @param liqAmt Amount0 Max amount * @param minAmtA Min AmountA amount * @param minAmtB Min AmountB amount * @param getId ID to retrieve liqAmt. * @param setIds Array of IDs tp stores the amounts of pools tokens received. */ function withdraw( address pool, uint256 liqAmt, uint256 minAmtA, uint256 minAmtB, uint256 getId, uint256[] calldata setIds ) external payable returns (string memory _eventName, bytes memory _eventParam) { liqAmt = getUint(getId, liqAmt); IGUniPool poolContract = IGUniPool(pool); (uint amount0, uint amount1, uint128 liquidityBurned) = poolContract.burn(liqAmt, address(this)); if (amount0 > 0) { IERC20 _token0 = poolContract.token0(); convertWethToEth(address(_token0) == wethAddr, TokenInterface(address(_token0)), amount0); } if (amount1 > 0) { IERC20 _token1 = poolContract.token1(); convertWethToEth(address(_token1) == wethAddr, TokenInterface(address(_token1)), amount1); } require(amount0 >= minAmtA && amount1 >= minAmtB, "received below minimum"); setUint(setIds[0], amount0); setUint(setIds[1], amount1); _eventName = "LogWithdrawLiquidity(address,uint256,uint256,uint256,uint256,uint256[])"; _eventParam = abi.encode(pool, amount0, amount1, uint256(liquidityBurned), getId, setIds); } /** * @dev Swap & Deposit Liquidity. * @notice Withdraw Liquidity to Gelato Uniswap V3 pool. * @param pool The address of pool. * @param amount0In amount of token0 to deposit. * @param amount1In amount of token1 to deposit. * @param zeroForOne Swap excess of one token to deposit in equal ratio. * @param swapAmount Amount of tokens to swap * @param swapThreshold Slippage that the swap could take. * @param getId Not used anywhere here. * @param setId Set the amount of tokens minted. */ function swapAndDeposit( address pool, uint256 amount0In, uint256 amount1In, bool zeroForOne, uint256 swapAmount, uint160 swapThreshold, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { DepositAndSwap memory depositAndSwap; depositAndSwap.poolContract = IGUniPool(pool); depositAndSwap._token0 = depositAndSwap.poolContract.token0(); depositAndSwap._token1 = depositAndSwap.poolContract.token1(); depositAndSwap.amount0; depositAndSwap.amount1; depositAndSwap.mintAmount; if (address(depositAndSwap._token0) == wethAddr) { approve(TokenInterface(address(depositAndSwap._token1)), address(gUniRouter), amount1In); (depositAndSwap.amount0, depositAndSwap.amount1, depositAndSwap.mintAmount) = gUniRouter.rebalanceAndAddLiquidityETH{value: amount0In}( depositAndSwap.poolContract, amount0In, amount1In, zeroForOne, swapAmount, swapThreshold, 0, 0, address(this) ); } else if (address(depositAndSwap._token1) == wethAddr) { approve(TokenInterface(address(depositAndSwap._token0)), address(gUniRouter), amount0In); (depositAndSwap.amount0, depositAndSwap.amount1,depositAndSwap. mintAmount) = gUniRouter.rebalanceAndAddLiquidityETH{value: amount1In}( depositAndSwap.poolContract, amount0In, amount1In, zeroForOne, swapAmount, swapThreshold, 0, 0, address(this) ); } else { approve(TokenInterface(address(depositAndSwap._token0)), address(gUniRouter), amount0In); approve(TokenInterface(address(depositAndSwap._token1)), address(gUniRouter), amount1In); (depositAndSwap.amount0, depositAndSwap.amount1, depositAndSwap.mintAmount) = gUniRouter.rebalanceAndAddLiquidity( depositAndSwap.poolContract, amount0In, amount1In, zeroForOne, swapAmount, swapThreshold, 0, 0, address(this) ); } setUint(setId, depositAndSwap.mintAmount); _eventName = "LogSwapAndDepositLiquidity(address,uint256,uint256,uint256,bool,uint256,uint256,uint256)"; _eventParam = abi.encode( pool, depositAndSwap.amount0, depositAndSwap.amount1, depositAndSwap.mintAmount, zeroForOne, swapAmount, getId, setId ); } } contract ConnectV2GUniswapV3ERC20 is UniswapV3Resolver { string public constant name = "G-Uniswap-v3-ERC20-v1.0"; }
Withdraw Liquidity. Withdraw Liquidity from Gelato Uniswap V3 pool. pool The address of pool. liqAmt Amount0 Max amount minAmtA Min AmountA amount minAmtB Min AmountB amount getId ID to retrieve liqAmt. setIds Array of IDs tp stores the amounts of pools tokens received./
function withdraw( address pool, uint256 liqAmt, uint256 minAmtA, uint256 minAmtB, uint256 getId, uint256[] calldata setIds ) external payable returns (string memory _eventName, bytes memory _eventParam) { liqAmt = getUint(getId, liqAmt); IGUniPool poolContract = IGUniPool(pool); (uint amount0, uint amount1, uint128 liquidityBurned) = poolContract.burn(liqAmt, address(this)); if (amount0 > 0) { IERC20 _token0 = poolContract.token0(); convertWethToEth(address(_token0) == wethAddr, TokenInterface(address(_token0)), amount0); } if (amount1 > 0) { IERC20 _token1 = poolContract.token1(); convertWethToEth(address(_token1) == wethAddr, TokenInterface(address(_token1)), amount1); } require(amount0 >= minAmtA && amount1 >= minAmtB, "received below minimum"); setUint(setIds[0], amount0); setUint(setIds[1], amount1); _eventName = "LogWithdrawLiquidity(address,uint256,uint256,uint256,uint256,uint256[])"; _eventParam = abi.encode(pool, amount0, amount1, uint256(liquidityBurned), getId, setIds); }
1,771,288
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import "./ERC1404.sol"; import "./roles/OwnerRole.sol"; import "./capabilities/Proxiable.sol"; import "./capabilities/Burnable.sol"; import "./capabilities/Mintable.sol"; import "./capabilities/Pausable.sol"; import "./capabilities/Revocable.sol"; import "./capabilities/Blacklistable.sol"; import "./capabilities/Whitelistable.sol"; import "./capabilities/RevocableToAddress.sol"; /// @title Wrapped Token V1 Contract /// @notice The role based access controls allow the Owner accounts to determine which permissions are granted to admin /// accounts. Admin accounts can enable, disable, and configure the token restrictions built into the contract. /// @dev This contract implements the ERC1404 Interface to add transfer restrictions to a standard ERC20 token. contract WrappedTokenV1 is Proxiable, ERC20Upgradeable, ERC1404, OwnerRole, Whitelistable, Mintable, Burnable, Revocable, Pausable, Blacklistable, RevocableToAddress { AggregatorV3Interface public reserveFeed; // ERC1404 Error codes and messages uint8 public constant SUCCESS_CODE = 0; uint8 public constant FAILURE_NON_WHITELIST = 1; uint8 public constant FAILURE_PAUSED = 2; string public constant SUCCESS_MESSAGE = "SUCCESS"; string public constant FAILURE_NON_WHITELIST_MESSAGE = "The transfer was restricted due to white list configuration."; string public constant FAILURE_PAUSED_MESSAGE = "The transfer was restricted due to the contract being paused."; string public constant UNKNOWN_ERROR = "Unknown Error Code"; /// @notice The from/to account has been explicitly denied the ability to send/receive uint8 public constant FAILURE_BLACKLIST = 3; string public constant FAILURE_BLACKLIST_MESSAGE = "Restricted due to blacklist"; event OracleAddressUpdated(address newAddress); constructor( string memory name, string memory symbol, AggregatorV3Interface resFeed ) { initialize(msg.sender, name, symbol, 0, resFeed, true, false); } /// @notice This method can only be called once for a unique contract address /// @dev Initialization for the token to set readable details and mint all tokens to the specified owner /// @param owner Owner address for the contract /// @param name Token name identifier /// @param symbol Token symbol identifier /// @param initialSupply Amount minted to the owner /// @param resFeed oracle contract address /// @param whitelistEnabled A boolean flag that enables token transfers to be white listed /// @param flashMintEnabled A boolean flag that enables tokens to be flash minted function initialize( address owner, string memory name, string memory symbol, uint256 initialSupply, AggregatorV3Interface resFeed, bool whitelistEnabled, bool flashMintEnabled ) public initializer { reserveFeed = resFeed; ERC20Upgradeable.__ERC20_init(name, symbol); Mintable._mint(msg.sender, owner, initialSupply); OwnerRole._addOwner(owner); Mintable._setFlashMintEnabled(flashMintEnabled); Whitelistable._setWhitelistEnabled(whitelistEnabled); Mintable._setFlashMintFeeReceiver(owner); } /// @dev Public function to update the address of the code contract /// @param newAddress new implementation contract address function updateCodeAddress(address newAddress) external onlyOwner { Proxiable._updateCodeAddress(newAddress); } /// @dev Public function to update the address of the code oracle, retricted to owner /// @param resFeed oracle contract address function updateOracleAddress(AggregatorV3Interface resFeed) external onlyOwner { reserveFeed = resFeed; mint(msg.sender, 0); emit OracleAddressUpdated(address(reserveFeed)); } /// @notice If the function returns SUCCESS_CODE (0) then it should be allowed /// @dev Public function detects whether a transfer should be restricted and not allowed /// @param from The sender of a token transfer /// @param to The receiver of a token transfer /// function detectTransferRestriction( address from, address to, uint256 ) public view override returns (uint8) { // Restrictions are enabled, so verify the whitelist config allows the transfer. // Logic defined in Blacklistable parent class if (!checkBlacklistAllowed(from, to)) { return FAILURE_BLACKLIST; } // Check the paused status of the contract if (Pausable.paused()) { return FAILURE_PAUSED; } // If an owner transferring, then ignore whitelist restrictions if (OwnerRole.isOwner(from)) { return SUCCESS_CODE; } // Restrictions are enabled, so verify the whitelist config allows the transfer. // Logic defined in Whitelistable parent class if (!checkWhitelistAllowed(from, to)) { return FAILURE_NON_WHITELIST; } // If no restrictions were triggered return success return SUCCESS_CODE; } /// @notice It should return enough information for the user to know why it failed. /// @dev Public function allows a wallet or other client to get a human readable string to show a user if a transfer /// was restricted. /// @param restrictionCode The sender of a token transfer function messageForTransferRestriction(uint8 restrictionCode) public pure override returns (string memory) { if (restrictionCode == FAILURE_BLACKLIST) { return FAILURE_BLACKLIST_MESSAGE; } if (restrictionCode == SUCCESS_CODE) { return SUCCESS_MESSAGE; } if (restrictionCode == FAILURE_NON_WHITELIST) { return FAILURE_NON_WHITELIST_MESSAGE; } if (restrictionCode == FAILURE_PAUSED) { return FAILURE_PAUSED_MESSAGE; } // An unknown error code was passed in. return UNKNOWN_ERROR; } /// @dev Modifier that evaluates whether a transfer should be allowed or not /// @param from The sender of a token transfer /// @param to The receiver of a token transfer /// @param value Quantity of tokens being exchanged between the sender and receiver modifier notRestricted( address from, address to, uint256 value ) { uint8 restrictionCode = detectTransferRestriction(from, to, value); require( restrictionCode == SUCCESS_CODE, messageForTransferRestriction(restrictionCode) ); _; } /// @dev Public function that overrides the parent class token transfer function to enforce restrictions /// @param to Receiver of the token transfer /// @param value Amount of tokens to transfer /// @return success Status of the transfer function transfer(address to, uint256 value) public override notRestricted(msg.sender, to, value) returns (bool success) { success = ERC20Upgradeable.transfer(to, value); } /// @dev Public function that overrides the parent class token transferFrom function to enforce restrictions /// @param from Sender of the token transfer /// @param to Receiver of the token transfer /// @param value Amount of tokens to transfer /// @return success Status of the transfer function transferFrom( address from, address to, uint256 value ) public override notRestricted(from, to, value) returns (bool success) { success = ERC20Upgradeable.transferFrom(from, to, value); } /// @dev Public function to recover all ether sent to this contract to an owner address function withdraw() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } /// @dev Public function to recover all tokens sent to this contract to an owner address /// @param token ERC20 that has a balance for this contract address /// @return success Status of the transfer function recover(IERC20Upgradeable token) external onlyOwner returns (bool success) { success = token.transfer(msg.sender, token.balanceOf(address(this))); } /// @dev Allow Owners to mint tokens to valid addresses /// @param account The account tokens will be added to /// @param amount The number of tokens to add to a balance function mint(address account, uint256 amount) public override onlyMinter returns (bool) { uint256 total = amount + ERC20Upgradeable.totalSupply(); (, int256 answer, , , ) = reserveFeed.latestRoundData(); uint256 decimals = ERC20Upgradeable.decimals(); uint256 reserveFeedDecimals = reserveFeed.decimals(); require(decimals >= reserveFeedDecimals, "invalid price feed decimals"); require( (answer > 0) && (uint256(answer) * 10**uint256(decimals - reserveFeedDecimals) > total), "reserve must exceed the total supply" ); return Mintable.mint(account, amount); } /// @dev Overrides the parent hook which is called ahead of `transfer` every time that method is called /// @param from Sender of the token transfer /// @param amount Amount of token being transferred function _beforeTokenTransfer( address from, address, uint256 amount ) internal view override { if (from != address(0)) { return; } require( ERC20FlashMintUpgradeable.maxFlashLoan(address(this)) > amount, "mint exceeds max allowed" ); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title WhitelisterRole Contract /// @notice Only administrators can update the white lister roles /// @dev Keeps track of white listers and can check if an account is authorized contract WhitelisterRole is OwnerRole { event WhitelisterAdded( address indexed addedWhitelister, address indexed addedBy ); event WhitelisterRemoved( address indexed removedWhitelister, address indexed removedBy ); Role private _whitelisters; /// @dev Modifier to make a function callable only when the caller is a white lister modifier onlyWhitelister() { require( isWhitelister(msg.sender), "WhitelisterRole: caller does not have the Whitelister role" ); _; } /// @dev Public function returns `true` if `account` has been granted a white lister role function isWhitelister(address account) public view returns (bool) { return _has(_whitelisters, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a white lister /// @param account The address that is guaranteed white lister authorization function _addWhitelister(address account) internal { _add(_whitelisters, account); emit WhitelisterAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a white lister /// @param account The address removed as a white lister function _removeWhitelister(address account) internal { _remove(_whitelisters, account); emit WhitelisterRemoved(account, msg.sender); } /// @dev Public function that adds an address as a white lister /// @param account The address that is guaranteed white lister authorization function addWhitelister(address account) external onlyOwner { _addWhitelister(account); } /// @dev Public function that removes an account from being a white lister /// @param account The address removed as a white lister function removeWhitelister(address account) external onlyOwner { _removeWhitelister(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title RevokerRole Contract /// @notice Only administrators can update the revoker roles /// @dev Keeps track of revokers and can check if an account is authorized contract RevokerRole is OwnerRole { event RevokerAdded(address indexed addedRevoker, address indexed addedBy); event RevokerRemoved( address indexed removedRevoker, address indexed removedBy ); Role private _revokers; /// @dev Modifier to make a function callable only when the caller is a revoker modifier onlyRevoker() { require( isRevoker(msg.sender), "RevokerRole: caller does not have the Revoker role" ); _; } /// @dev Public function returns `true` if `account` has been granted a revoker role function isRevoker(address account) public view returns (bool) { return _has(_revokers, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a revoker /// @param account The address that is guaranteed revoker authorization function _addRevoker(address account) internal { _add(_revokers, account); emit RevokerAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a revoker /// @param account The address removed as a revoker function _removeRevoker(address account) internal { _remove(_revokers, account); emit RevokerRemoved(account, msg.sender); } /// @dev Public function that adds an address as a revoker /// @param account The address that is guaranteed revoker authorization function addRevoker(address account) external onlyOwner { _addRevoker(account); } /// @dev Public function that removes an account from being a revoker /// @param account The address removed as a revoker function removeRevoker(address account) external onlyOwner { _removeRevoker(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title PauserRole Contract /// @notice Only administrators can update the pauser roles /// @dev Keeps track of pausers and can check if an account is authorized contract PauserRole is OwnerRole { event PauserAdded(address indexed addedPauser, address indexed addedBy); event PauserRemoved( address indexed removedPauser, address indexed removedBy ); Role private _pausers; /// @dev Modifier to make a function callable only when the caller is a pauser modifier onlyPauser() { require( isPauser(msg.sender), "PauserRole: caller does not have the Pauser role" ); _; } /// @dev Public function returns `true` if `account` has been granted a pauser role function isPauser(address account) public view returns (bool) { return _has(_pausers, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a pauser /// @param account The address that is guaranteed pauser authorization function _addPauser(address account) internal { _add(_pausers, account); emit PauserAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a pauser /// @param account The address removed as a pauser function _removePauser(address account) internal { _remove(_pausers, account); emit PauserRemoved(account, msg.sender); } /// @dev Public function that adds an address as a pauser /// @param account The address that is guaranteed pauser authorization function addPauser(address account) external onlyOwner { _addPauser(account); } /// @dev Public function that removes an account from being a pauser /// @param account The address removed as a pauser function removePauser(address account) external onlyOwner { _removePauser(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title OwnerRole Contract /// @notice Only administrators can update the owner roles /// @dev Keeps track of owners and can check if an account is authorized contract OwnerRole { event OwnerAdded(address indexed addedOwner, address indexed addedBy); event OwnerRemoved(address indexed removedOwner, address indexed removedBy); struct Role { mapping(address => bool) members; } Role private _owners; /// @dev Modifier to make a function callable only when the caller is an owner modifier onlyOwner() { require( isOwner(msg.sender), "OwnerRole: caller does not have the Owner role" ); _; } /// @dev Public function returns `true` if `account` has been granted an owner role function isOwner(address account) public view returns (bool) { return _has(_owners, account); } /// @dev Public function that adds an address as an owner /// @param account The address that is guaranteed owner authorization function addOwner(address account) external onlyOwner { _addOwner(account); } /// @dev Public function that removes an account from being an owner /// @param account The address removed as a owner function removeOwner(address account) external onlyOwner { _removeOwner(account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as an owner /// @param account The address that is guaranteed owner authorization function _addOwner(address account) internal { _add(_owners, account); emit OwnerAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being an owner /// @param account The address removed as an owner function _removeOwner(address account) internal { _remove(_owners, account); emit OwnerRemoved(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Give an account access to this role /// @param role All authorizations for the contract /// @param account The address that is guaranteed owner authorization function _add(Role storage role, address account) internal { require(account != address(0x0), "Invalid 0x0 address"); require(!_has(role, account), "Roles: account already has role"); role.members[account] = true; } /// @notice Only administrators should be allowed to update this /// @dev Remove an account's access to this role /// @param role All authorizations for the contract /// @param account The address that is guaranteed owner authorization function _remove(Role storage role, address account) internal { require(_has(role, account), "Roles: account does not have role"); role.members[account] = false; } /// @dev Check if an account is in the set of roles /// @param role All authorizations for the contract /// @param account The address that is guaranteed owner authorization /// @return boolean function _has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.members[account]; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title MinterRole Contract /// @notice Only administrators can update the minter roles /// @dev Keeps track of minters and can check if an account is authorized contract MinterRole is OwnerRole { event MinterAdded(address indexed addedMinter, address indexed addedBy); event MinterRemoved( address indexed removedMinter, address indexed removedBy ); Role private _minters; /// @dev Modifier to make a function callable only when the caller is a minter modifier onlyMinter() { require( isMinter(msg.sender), "MinterRole: caller does not have the Minter role" ); _; } /// @dev Public function returns `true` if `account` has been granted a minter role function isMinter(address account) public view returns (bool) { return _has(_minters, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a minter /// @param account The address that is guaranteed minter authorization function _addMinter(address account) internal { _add(_minters, account); emit MinterAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a minter /// @param account The address removed as a minter function _removeMinter(address account) internal { _remove(_minters, account); emit MinterRemoved(account, msg.sender); } /// @dev Public function that adds an address as a minter /// @param account The address that is guaranteed minter authorization function addMinter(address account) external onlyOwner { _addMinter(account); } /// @dev Public function that removes an account from being a minter /// @param account The address removed as a minter function removeMinter(address account) external onlyOwner { _removeMinter(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title BurnerRole Contract /// @notice Only administrators can update the burner roles /// @dev Keeps track of burners and can check if an account is authorized contract BurnerRole is OwnerRole { event BurnerAdded(address indexed addedBurner, address indexed addedBy); event BurnerRemoved( address indexed removedBurner, address indexed removedBy ); Role private _burners; /// @dev Modifier to make a function callable only when the caller is a burner modifier onlyBurner() { require( isBurner(msg.sender), "BurnerRole: caller does not have the Burner role" ); _; } /// @dev Public function returns `true` if `account` has been granted a burner role function isBurner(address account) public view returns (bool) { return _has(_burners, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a burner /// @param account The address that is guaranteed burner authorization function _addBurner(address account) internal { _add(_burners, account); emit BurnerAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a burner /// @param account The address removed as a burner function _removeBurner(address account) internal { _remove(_burners, account); emit BurnerRemoved(account, msg.sender); } /// @dev Public function that adds an address as a burner /// @param account The address that is guaranteed burner authorization function addBurner(address account) external onlyOwner { _addBurner(account); } /// @dev Public function that removes an account from being a burner /// @param account The address removed as a burner function removeBurner(address account) external onlyOwner { _removeBurner(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title BlacklisterRole Contract /// @notice Only administrators can update the black lister roles /// @dev Keeps track of black listers and can check if an account is authorized contract BlacklisterRole is OwnerRole { event BlacklisterAdded( address indexed addedBlacklister, address indexed addedBy ); event BlacklisterRemoved( address indexed removedBlacklister, address indexed removedBy ); Role private _Blacklisters; /// @dev Modifier to make a function callable only when the caller is a black lister modifier onlyBlacklister() { require(isBlacklister(msg.sender), "BlacklisterRole missing"); _; } /// @dev Public function returns `true` if `account` has been granted a black lister role function isBlacklister(address account) public view returns (bool) { return _has(_Blacklisters, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a black lister /// @param account The address that is guaranteed black lister authorization function _addBlacklister(address account) internal { _add(_Blacklisters, account); emit BlacklisterAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a black lister /// @param account The address removed as a black lister function _removeBlacklister(address account) internal { _remove(_Blacklisters, account); emit BlacklisterRemoved(account, msg.sender); } /// @dev Public function that adds an address as a black lister /// @param account The address that is guaranteed black lister authorization function addBlacklister(address account) external onlyOwner { _addBlacklister(account); } /// @dev Public function that removes an account from being a black lister /// @param account The address removed as a black lister function removeBlacklister(address account) external onlyOwner { _removeBlacklister(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../roles/WhitelisterRole.sol"; /// @title Whitelistable Contract /// @notice Only administrators can update the white lists, and any address can only be a member of one whitelist at a /// time /// @dev Keeps track of white lists and can check if sender and reciever are configured to allow a transfer contract Whitelistable is WhitelisterRole { // The mapping to keep track of which whitelist any address belongs to. // 0 is reserved for no whitelist and is the default for all addresses. mapping(address => uint8) public addressWhitelists; // The mapping to keep track of each whitelist's outbound whitelist flags. // Boolean flag indicates whether outbound transfers are enabled. mapping(uint8 => mapping(uint8 => bool)) public outboundWhitelistsEnabled; // Track whether whitelisting is enabled bool public isWhitelistEnabled; // Zero is reserved for indicating it is not on a whitelist uint8 constant NO_WHITELIST = 0; // Events to allow tracking add/remove. event AddressAddedToWhitelist( address indexed addedAddress, uint8 indexed whitelist, address indexed addedBy ); event AddressRemovedFromWhitelist( address indexed removedAddress, uint8 indexed whitelist, address indexed removedBy ); event OutboundWhitelistUpdated( address indexed updatedBy, uint8 indexed sourceWhitelist, uint8 indexed destinationWhitelist, bool from, bool to ); event WhitelistEnabledUpdated( address indexed updatedBy, bool indexed enabled ); /// @notice Only administrators should be allowed to update this /// @dev Enable or disable the whitelist enforcement /// @param enabled A boolean flag that enables token transfers to be white listed function _setWhitelistEnabled(bool enabled) internal { isWhitelistEnabled = enabled; emit WhitelistEnabledUpdated(msg.sender, enabled); } /// @notice Only administrators should be allowed to update this. If an address is on an existing whitelist, it will /// just get updated to the new value (removed from previous) /// @dev Sets an address's white list ID. /// @param addressToAdd The address added to a whitelist /// @param whitelist Number identifier for the whitelist the address is being added to function _addToWhitelist(address addressToAdd, uint8 whitelist) internal { // Verify a valid address was passed in require( addressToAdd != address(0), "Cannot add address 0x0 to a whitelist." ); // Verify the whitelist is valid require(whitelist != NO_WHITELIST, "Invalid whitelist ID supplied"); // Save off the previous white list uint8 previousWhitelist = addressWhitelists[addressToAdd]; // Set the address's white list ID addressWhitelists[addressToAdd] = whitelist; // If the previous whitelist existed then we want to indicate it has been removed if (previousWhitelist != NO_WHITELIST) { // Emit the event for tracking emit AddressRemovedFromWhitelist( addressToAdd, previousWhitelist, msg.sender ); } // Emit the event for new whitelist emit AddressAddedToWhitelist(addressToAdd, whitelist, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Clears out an address's white list ID /// @param addressToRemove The address removed from a white list function _removeFromWhitelist(address addressToRemove) internal { // Verify a valid address was passed in require( addressToRemove != address(0), "Cannot remove address 0x0 from a whitelist." ); // Save off the previous white list uint8 previousWhitelist = addressWhitelists[addressToRemove]; // Verify the address was actually on a whitelist require( previousWhitelist != NO_WHITELIST, "Address cannot be removed from invalid whitelist." ); // Zero out the previous white list addressWhitelists[addressToRemove] = NO_WHITELIST; // Emit the event for tracking emit AddressRemovedFromWhitelist( addressToRemove, previousWhitelist, msg.sender ); } /// @notice Only administrators should be allowed to update this /// @dev Sets the flag to indicate whether source whitelist is allowed to send to destination whitelist /// @param sourceWhitelist The white list of the sender /// @param destinationWhitelist The white list of the receiver /// @param newEnabledValue A boolean flag that enables token transfers between white lists function _updateOutboundWhitelistEnabled( uint8 sourceWhitelist, uint8 destinationWhitelist, bool newEnabledValue ) internal { // Get the old enabled flag bool oldEnabledValue = outboundWhitelistsEnabled[sourceWhitelist][ destinationWhitelist ]; // Update to the new value outboundWhitelistsEnabled[sourceWhitelist][ destinationWhitelist ] = newEnabledValue; // Emit event for tracking emit OutboundWhitelistUpdated( msg.sender, sourceWhitelist, destinationWhitelist, oldEnabledValue, newEnabledValue ); } /// @notice The source whitelist must be enabled to send to the whitelist where the receive exists /// @dev Determine if the a sender is allowed to send to the receiver /// @param sender The address of the sender /// @param receiver The address of the receiver function checkWhitelistAllowed(address sender, address receiver) public view returns (bool) { // If whitelist enforcement is not enabled, then allow all if (!isWhitelistEnabled) { return true; } // First get each address white list uint8 senderWhiteList = addressWhitelists[sender]; uint8 receiverWhiteList = addressWhitelists[receiver]; // If either address is not on a white list then the check should fail if ( senderWhiteList == NO_WHITELIST || receiverWhiteList == NO_WHITELIST ) { return false; } // Determine if the sending whitelist is allowed to send to the destination whitelist return outboundWhitelistsEnabled[senderWhiteList][receiverWhiteList]; } /// @dev Public function that enables or disables the white list enforcement /// @param enabled A boolean flag that enables token transfers to be whitelisted function setWhitelistEnabled(bool enabled) external onlyOwner { _setWhitelistEnabled(enabled); } /// @notice If an address is on an existing whitelist, it will just get updated to the new value (removed from /// previous) /// @dev Public function that sets an address's white list ID /// @param addressToAdd The address added to a whitelist /// @param whitelist Number identifier for the whitelist the address is being added to function addToWhitelist(address addressToAdd, uint8 whitelist) external onlyWhitelister { _addToWhitelist(addressToAdd, whitelist); } /// @dev Public function that clears out an address's white list ID /// @param addressToRemove The address removed from a white list function removeFromWhitelist(address addressToRemove) external onlyWhitelister { _removeFromWhitelist(addressToRemove); } /// @dev Public function that sets the flag to indicate whether source white list is allowed to send to destination /// white list /// @param sourceWhitelist The white list of the sender /// @param destinationWhitelist The white list of the receiver /// @param newEnabledValue A boolean flag that enables token transfers between white lists function updateOutboundWhitelistEnabled( uint8 sourceWhitelist, uint8 destinationWhitelist, bool newEnabledValue ) external onlyWhitelister { _updateOutboundWhitelistEnabled( sourceWhitelist, destinationWhitelist, newEnabledValue ); } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../roles/RevokerRole.sol"; /// @title RevocableToAddress Contract /// @notice Only administrators can revoke tokens to an address /// @dev Enables reducing a balance by transfering tokens to an address contract RevocableToAddress is ERC20Upgradeable, RevokerRole { event RevokeToAddress( address indexed revoker, address indexed from, address indexed to, uint256 amount ); /// @notice Only administrators should be allowed to revoke on behalf of another account /// @dev Revoke a quantity of token in an account, reducing the balance /// @param from The account tokens will be deducted from /// @param to The account revoked token will be transferred to /// @param amount The number of tokens to remove from a balance function _revokeToAddress( address from, address to, uint256 amount ) internal returns (bool) { ERC20Upgradeable._transfer(from, to, amount); emit RevokeToAddress(msg.sender, from, to, amount); return true; } /** Allow Admins to revoke tokens from any address to any destination */ /// @notice Only administrators should be allowed to revoke on behalf of another account /// @dev Revoke a quantity of token in an account, reducing the balance /// @param from The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function revokeToAddress( address from, address to, uint256 amount ) external onlyRevoker returns (bool) { return _revokeToAddress(from, to, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../roles/RevokerRole.sol"; /// @title Revocable Contract /// @notice Only administrators can revoke tokens /// @dev Enables reducing a balance by transfering tokens to the caller contract Revocable is ERC20Upgradeable, RevokerRole { event Revoke(address indexed revoker, address indexed from, uint256 amount); /// @notice Only administrators should be allowed to revoke on behalf of another account /// @dev Revoke a quantity of token in an account, reducing the balance /// @param from The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function _revoke(address from, uint256 amount) internal returns (bool) { ERC20Upgradeable._transfer(from, msg.sender, amount); emit Revoke(msg.sender, from, amount); return true; } /// @dev Allow Revokers to revoke tokens for addresses /// @param from The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function revoke(address from, uint256 amount) external onlyRevoker returns (bool) { return _revoke(from, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" uint256 constant PROXIABLE_MEM_SLOT = 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; event CodeAddressUpdated(address newAddress); function _updateCodeAddress(address newAddress) internal { require( bytes32(PROXIABLE_MEM_SLOT) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore(PROXIABLE_MEM_SLOT, newAddress) } emit CodeAddressUpdated(newAddress); } function getLogicAddress() external view returns (address logicAddress) { assembly { // solium-disable-line logicAddress := sload(PROXIABLE_MEM_SLOT) } } function proxiableUUID() external pure returns (bytes32) { return bytes32(PROXIABLE_MEM_SLOT); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../roles/PauserRole.sol"; /// @title Pausable Contract /// @notice Child contracts will not be pausable by simply including this module, but only once the modifiers are put in /// place /// @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. contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; /// @dev Returns true if the contract is paused, and false otherwise. /// @return A boolean flag for if the contract is paused function paused() public view returns (bool) { return _paused; } /// @dev Modifier to make a function callable only when the contract is not paused modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /// @dev Modifier to make a function callable only when the contract is paused modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /// @notice Only administrators should be allowed to update this /// @dev Triggers stopped state function _pause() internal { _paused = true; emit Paused(msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Resets to normal state function _unpause() internal { _paused = false; emit Unpaused(msg.sender); } /// @dev Public function triggers stopped state function pause() external onlyPauser whenNotPaused { Pausable._pause(); } /// @dev Public function resets to normal state. function unpause() external onlyPauser whenPaused { Pausable._unpause(); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20FlashMintUpgradeable.sol"; import "../roles/MinterRole.sol"; /// @title Mintable Contract /// @notice Only administrators can mint tokens /// @dev Enables increasing a balance by minting tokens contract Mintable is ERC20FlashMintUpgradeable, MinterRole, ReentrancyGuardUpgradeable { event Mint(address indexed minter, address indexed to, uint256 amount); uint256 public flashMintFee = 0; address public flashMintFeeReceiver; bool public isFlashMintEnabled = false; bytes32 public constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan"); /// @notice Only administrators should be allowed to mint on behalf of another account /// @dev Mint a quantity of token in an account, increasing the balance /// @param minter Designated to be allowed to mint account tokens /// @param to The account tokens will be increased to /// @param amount The number of tokens to add to a balance function _mint( address minter, address to, uint256 amount ) internal returns (bool) { ERC20Upgradeable._mint(to, amount); emit Mint(minter, to, amount); return true; } /// @notice Only administrators should be allowed to update this /// @dev Enable or disable the flash mint functionality /// @param enabled A boolean flag that enables tokens to be flash minted function _setFlashMintEnabled(bool enabled) internal { isFlashMintEnabled = enabled; } /// @notice Only administrators should be allowed to update this /// @dev Sets the address that will receive fees of flash mints /// @param receiver The account that will receive flash mint fees function _setFlashMintFeeReceiver(address receiver) internal { flashMintFeeReceiver = receiver; } /// @dev Allow Owners to mint tokens to valid addresses /// @param account The account tokens will be added to /// @param amount The number of tokens to add to a balance function mint(address account, uint256 amount) public virtual onlyMinter returns (bool) { return Mintable._mint(msg.sender, account, amount); } /// @dev Public function to set the fee paid by the borrower for a flash mint /// @param fee The number of tokens that will cost to flash mint function setFlashMintFee(uint256 fee) external onlyMinter { flashMintFee = fee; } /// @dev Public function to enable or disable the flash mint functionality /// @param enabled A boolean flag that enables tokens to be flash minted function setFlashMintEnabled(bool enabled) external onlyMinter { _setFlashMintEnabled(enabled); } /// @dev Public function to update the receiver of the fee paid for a flash mint /// @param receiver The account that will receive flash mint fees function setFlashMintFeeReceiver(address receiver) external onlyMinter { _setFlashMintFeeReceiver(receiver); } /// @dev Public function that returns the fee set for a flash mint /// @param token The token to be flash loaned /// @return The fees applied to the corresponding flash loan function flashFee(address token, uint256) public view override returns (uint256) { require(token == address(this), "ERC20FlashMint: wrong token"); return flashMintFee; } /// @dev Performs a flash loan. New tokens are minted and sent to the /// `receiver`, who is required to implement the {IERC3156FlashBorrower} /// interface. By the end of the flash loan, the receiver is expected to own /// amount + fee tokens so that the fee can be sent to the fee receiver and the /// amount minted should be burned before the transaction completes /// @param receiver The receiver of the flash loan. Should implement the /// {IERC3156FlashBorrower.onFlashLoan} interface /// @param token The token to be flash loaned. Only `address(this)` is /// supported /// @param amount The amount of tokens to be loaned /// @param data An arbitrary datafield that is passed to the receiver /// @return `true` if the flash loan was successful function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes calldata data ) public override nonReentrant returns (bool) { require(isFlashMintEnabled, "flash mint is disabled"); uint256 fee = flashFee(token, amount); _mint(address(receiver), amount); require( receiver.onFlashLoan(msg.sender, token, amount, fee, data) == _RETURN_VALUE, "ERC20FlashMint: invalid return value" ); uint256 currentAllowance = allowance(address(receiver), address(this)); require( currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund" ); _transfer(address(receiver), flashMintFeeReceiver, fee); _approve( address(receiver), address(this), currentAllowance - amount - fee ); _burn(address(receiver), amount); return true; } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../roles/BurnerRole.sol"; /// @title Burnable Contract /// @notice Only administrators can burn tokens /// @dev Enables reducing a balance by burning tokens contract Burnable is ERC20Upgradeable, BurnerRole { event Burn(address indexed burner, address indexed from, uint256 amount); /// @notice Only administrators should be allowed to burn on behalf of another account /// @dev Burn a quantity of token in an account, reducing the balance /// @param burner Designated to be allowed to burn account tokens /// @param from The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function _burn( address burner, address from, uint256 amount ) internal returns (bool) { ERC20Upgradeable._burn(from, amount); emit Burn(burner, from, amount); return true; } /// @dev Allow Burners to burn tokens for addresses /// @param account The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function burn(address account, uint256 amount) external onlyBurner returns (bool) { return _burn(msg.sender, account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../roles/BlacklisterRole.sol"; /// @title Blacklistable Contract /// @notice Only administrators can update the black list /// @dev Keeps track of black lists and can check if sender and reciever are configured to allow a transfer contract Blacklistable is BlacklisterRole { // The mapping to keep track if an address is black listed mapping(address => bool) public addressBlacklists; // Track whether Blacklisting is enabled bool public isBlacklistEnabled; // Events to allow tracking add/remove. event AddressAddedToBlacklist( address indexed addedAddress, address indexed addedBy ); event AddressRemovedFromBlacklist( address indexed removedAddress, address indexed removedBy ); event BlacklistEnabledUpdated( address indexed updatedBy, bool indexed enabled ); /// @notice Only administrators should be allowed to update this /// @dev Enable or disable the black list enforcement /// @param enabled A boolean flag that enables token transfers to be black listed function _setBlacklistEnabled(bool enabled) internal { isBlacklistEnabled = enabled; emit BlacklistEnabledUpdated(msg.sender, enabled); } /// @notice Only administrators should be allowed to update this /// @dev Sets an address's black listing status /// @param addressToAdd The address added to a black list function _addToBlacklist(address addressToAdd) internal { // Verify a valid address was passed in require(addressToAdd != address(0), "Cannot add 0x0"); // Verify the address is on the blacklist before it can be removed require(!addressBlacklists[addressToAdd], "Already on list"); // Set the address's white list ID addressBlacklists[addressToAdd] = true; // Emit the event for new Blacklist emit AddressAddedToBlacklist(addressToAdd, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Clears out an address from the black list /// @param addressToRemove The address removed from a black list function _removeFromBlacklist(address addressToRemove) internal { // Verify a valid address was passed in require(addressToRemove != address(0), "Cannot remove 0x0"); // Verify the address is on the blacklist before it can be removed require(addressBlacklists[addressToRemove], "Not on list"); // Zero out the previous white list addressBlacklists[addressToRemove] = false; // Emit the event for tracking emit AddressRemovedFromBlacklist(addressToRemove, msg.sender); } /// @notice If either the sender or receiver is black listed, then the transfer should be denied /// @dev Determine if the a sender is allowed to send to the receiver /// @param sender The sender of a token transfer /// @param receiver The receiver of a token transfer function checkBlacklistAllowed(address sender, address receiver) public view returns (bool) { // If black list enforcement is not enabled, then allow all if (!isBlacklistEnabled) { return true; } // If either address is on the black list then fail return !addressBlacklists[sender] && !addressBlacklists[receiver]; } /// @dev Public function that enables or disables the black list enforcement /// @param enabled A boolean flag that enables token transfers to be black listed function setBlacklistEnabled(bool enabled) external onlyOwner { _setBlacklistEnabled(enabled); } /// @dev Public function that allows admins to remove an address from a black list /// @param addressToAdd The address added to a black list function addToBlacklist(address addressToAdd) external onlyBlacklister { _addToBlacklist(addressToAdd); } /// @dev Public function that allows admins to remove an address from a black list /// @param addressToRemove The address removed from a black list function removeFromBlacklist(address addressToRemove) external onlyBlacklister { _removeFromBlacklist(addressToRemove); } uint256[48] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract ERC1404 { /// @notice Detects if a transfer will be reverted and if so returns an appropriate reference code /// @dev Overwrite with your custom transfer restriction logic /// @param from Sending address /// @param to Receiving address /// @param value Amount of tokens being transferred /// @return Code by which to reference message for rejection reasoning function detectTransferRestriction( address from, address to, uint256 value ) public view virtual returns (uint8); /// @notice Returns a human-readable message for a given restriction code /// @dev Overwrite with your custom message and restrictionCode handling /// @param restrictionCode Identifier for looking up a message /// @return Text showing the restriction's reasoning function messageForTransferRestriction(uint8 restrictionCode) public view virtual returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (token/ERC20/extensions/ERC20FlashMint.sol) pragma solidity ^0.8.0; import "../../../interfaces/IERC3156Upgradeable.sol"; import "../ERC20Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the ERC3156 Flash loans extension, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. * * Adds the {flashLoan} method, which provides flash loan support at the token * level. By default there is no fee, but this can be changed by overriding {flashFee}. * * _Available since v4.1._ */ abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable, IERC3156FlashLenderUpgradeable { function __ERC20FlashMint_init() internal initializer { __Context_init_unchained(); __ERC20FlashMint_init_unchained(); } function __ERC20FlashMint_init_unchained() internal initializer { } bytes32 private constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan"); /** * @dev Returns the maximum amount of tokens available for loan. * @param token The address of the token that is requested. * @return The amont of token that can be loaned. */ function maxFlashLoan(address token) public view override returns (uint256) { return token == address(this) ? type(uint256).max - ERC20Upgradeable.totalSupply() : 0; } /** * @dev Returns the fee applied when doing flash loans. By default this * implementation has 0 fees. This function can be overloaded to make * the flash loan mechanism deflationary. * @param token The token to be flash loaned. * @param amount The amount of tokens to be loaned. * @return The fees applied to the corresponding flash loan. */ function flashFee(address token, uint256 amount) public view virtual override returns (uint256) { require(token == address(this), "ERC20FlashMint: wrong token"); // silence warning about unused variable without the addition of bytecode. amount; return 0; } /** * @dev Performs a flash loan. New tokens are minted and sent to the * `receiver`, who is required to implement the {IERC3156FlashBorrower} * interface. By the end of the flash loan, the receiver is expected to own * amount + fee tokens and have them approved back to the token contract itself so * they can be burned. * @param receiver The receiver of the flash loan. Should implement the * {IERC3156FlashBorrower.onFlashLoan} interface. * @param token The token to be flash loaned. Only `address(this)` is * supported. * @param amount The amount of tokens to be loaned. * @param data An arbitrary datafield that is passed to the receiver. * @return `true` is the flash loan was successful. */ function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes calldata data ) public virtual override returns (bool) { uint256 fee = flashFee(token, amount); _mint(address(receiver), amount); require( receiver.onFlashLoan(msg.sender, token, amount, fee, data) == _RETURN_VALUE, "ERC20FlashMint: invalid return value" ); uint256 currentAllowance = allowance(address(receiver), address(this)); require(currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund"); _approve(address(receiver), address(this), currentAllowance - amount - fee); _burn(address(receiver), amount + fee); return true; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 `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.0 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./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}. */ 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 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_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract 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 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (interfaces/IERC3156.sol) pragma solidity ^0.8.0; import "./IERC3156FlashBorrowerUpgradeable.sol"; import "./IERC3156FlashLenderUpgradeable.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (interfaces/IERC3156FlashLender.sol) pragma solidity ^0.8.0; import "./IERC3156FlashBorrowerUpgradeable.sol"; /** * @dev Interface of the ERC3156 FlashLender, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. * * _Available since v4.1._ */ interface IERC3156FlashLenderUpgradeable { /** * @dev The amount of currency available to be lended. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan(address token) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee(address token, uint256 amount) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (interfaces/IERC3156FlashBorrower.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC3156 FlashBorrower, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. * * _Available since v4.1._ */ interface IERC3156FlashBorrowerUpgradeable { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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 ); }
Only administrators should be allowed to update this Sets the address that will receive fees of flash mints receiver The account that will receive flash mint fees
function _setFlashMintFeeReceiver(address receiver) internal { flashMintFeeReceiver = receiver; }
9,906,262
./full_match/1/0x9db4694BE49558ba5F3CD4C449988fc0AeBa6E94/sources/contracts/Vault.sol
Lock tokens locker The account that is locking tokens receiver The account that will be able to retrieve unlocked tokens startTime The unix timestamp when the lock period will start amount The amount of tokens being locked lockDurationInDays The lock period in days/ Transfer the tokens under the control of the vault contract
function lockTokens( address token, address locker, address receiver, uint256 startTime, uint256 amount, uint16 lockDurationInDays ) external { require(lockDurationInDays > 0, "Vault::lockTokens: duration must be > 0"); require(lockDurationInDays <= 25*365, "Vault::lockTokens: duration more than 25 years"); require(amount > 0, "Vault::lockTokens: amount not > 0"); require(IUniswapV2ERC20(token).transferFrom(locker, address(this), amount), "Vault::lockTokens: transfer failed"); uint256 lockStartTime = startTime == 0 ? block.timestamp : startTime; Lock memory lock = Lock({ token: token, receiver: receiver, startTime: lockStartTime, amount: amount, duration: lockDurationInDays, amountClaimed: 0 }); tokenLocks[numLocks] = lock; activeLocks[receiver].push(numLocks); emit LockCreated(token, locker, receiver, amount, lockStartTime, lockDurationInDays, numLocks); numLocks++; }
3,846,886
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.4; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {IStandardERC20} from '../../base/interfaces/IStandardERC20.sol'; import { MintableBurnableIERC20 } from '../../tokens/interfaces/MintableBurnableIERC20.sol'; import { IDerivativeDeployment } from '../common/interfaces/IDerivativeDeployment.sol'; import {IDerivativeMain} from '../common/interfaces/IDerivativeMain.sol'; import { OracleInterface } from '@uma/core/contracts/oracle/interfaces/OracleInterface.sol'; import { IdentifierWhitelistInterface } from '@uma/core/contracts/oracle/interfaces/IdentifierWhitelistInterface.sol'; import { AdministrateeInterface } from '@uma/core/contracts/oracle/interfaces/AdministrateeInterface.sol'; import {ISynthereumFinder} from '../../core/interfaces/IFinder.sol'; import {IDerivative} from '../common/interfaces/IDerivative.sol'; import {SynthereumInterfaces} from '../../core/Constants.sol'; import { OracleInterfaces } from '@uma/core/contracts/oracle/implementation/Constants.sol'; import {SafeMath} from '@openzeppelin/contracts/utils/math/SafeMath.sol'; import { SafeERC20 } from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import { FixedPoint } from '@uma/core/contracts/common/implementation/FixedPoint.sol'; import { PerpetualPositionManagerPoolPartyLib } from './PerpetualPositionManagerPoolPartyLib.sol'; import {FeePayerPartyLib} from '../common/FeePayerPartyLib.sol'; import { AccessControlEnumerable } from '@openzeppelin/contracts/access/AccessControlEnumerable.sol'; import { AddressWhitelistInterface } from '@uma/core/contracts/common/interfaces/AddressWhitelistInterface.sol'; import {FeePayerParty} from '../common/FeePayerParty.sol'; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManagerPoolParty is IDerivative, AccessControlEnumerable, FeePayerParty { using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for MintableBurnableIERC20; using PerpetualPositionManagerPoolPartyLib for PositionData; using PerpetualPositionManagerPoolPartyLib for PositionManagerData; using FeePayerPartyLib for FixedPoint.Unsigned; bytes32 public constant POOL_ROLE = keccak256('Pool'); /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param collateralAddress ERC20 token used as collateral for all positions. * @param tokenAddress ERC20 token used as synthetic token. * @param finderAddress UMA protocol Finder used to discover other protocol contracts. * @param priceFeedIdentifier registered in the DVM for the synthetic. * @param minSponsorTokens minimum amount of collateral that must exist at any time in a position. * @param timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. * @param excessTokenBeneficiary Beneficiary to send all excess token balances that accrue in the contract. * @param synthereumFinder The SynthereumFinder contract */ struct PositionManagerParams { uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; address timerAddress; address excessTokenBeneficiary; ISynthereumFinder synthereumFinder; } //Describe role structure struct Roles { address[] admins; address[] pools; } // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } struct GlobalPositionData { // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned rawTotalPositionCollateral; } struct PositionManagerData { // SynthereumFinder contract ISynthereumFinder synthereumFinder; // Synthetic token created by this contract. MintableBurnableIERC20 tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned emergencyShutdownPrice; // Timestamp used in case of emergency shutdown. uint256 emergencyShutdownTimestamp; // The excessTokenBeneficiary of any excess tokens added to the contract. address excessTokenBeneficiary; } //---------------------------------------- // Storage //---------------------------------------- // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; GlobalPositionData public globalPositionData; PositionManagerData public positionManagerData; //---------------------------------------- // Events //---------------------------------------- event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal( address indexed sponsor, uint256 indexed collateralAmount ); event RequestWithdrawalExecuted( address indexed sponsor, uint256 indexed collateralAmount ); event RequestWithdrawalCanceled( address indexed sponsor, uint256 indexed collateralAmount ); event PositionCreated( address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount ); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem( address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount ); event Repay( address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount ); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); //---------------------------------------- // Modifiers //---------------------------------------- modifier onlyPool() { require(hasRole(POOL_ROLE, msg.sender), 'Sender must be a pool'); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } //---------------------------------------- // Constructor //---------------------------------------- /** * @notice Construct the PerpetualPositionManager. * @param _positionManagerData Input parameters of PositionManager (see PositionManagerData struct) * @param _roles List of admin and token sponsors roles */ constructor( PositionManagerParams memory _positionManagerData, Roles memory _roles ) FeePayerParty( _positionManagerData.collateralAddress, _positionManagerData.finderAddress, _positionManagerData.timerAddress ) nonReentrant() { require( _getIdentifierWhitelist().isIdentifierSupported( _positionManagerData.priceFeedIdentifier ), 'Unsupported price identifier' ); require( _getCollateralWhitelist().isOnWhitelist( _positionManagerData.collateralAddress ), 'Collateral not whitelisted' ); _setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(POOL_ROLE, DEFAULT_ADMIN_ROLE); for (uint256 j = 0; j < _roles.admins.length; j++) { _setupRole(DEFAULT_ADMIN_ROLE, _roles.admins[j]); } for (uint256 j = 0; j < _roles.pools.length; j++) { _setupRole(POOL_ROLE, _roles.pools[j]); } positionManagerData.synthereumFinder = _positionManagerData .synthereumFinder; positionManagerData.withdrawalLiveness = _positionManagerData .withdrawalLiveness; positionManagerData.tokenCurrency = MintableBurnableIERC20( _positionManagerData.tokenAddress ); positionManagerData.minSponsorTokens = _positionManagerData .minSponsorTokens; positionManagerData.priceIdentifier = _positionManagerData .priceFeedIdentifier; positionManagerData.excessTokenBeneficiary = _positionManagerData .excessTokenBeneficiary; } //---------------------------------------- // External functions //---------------------------------------- /** * @notice Transfers `collateralAmount` of `feePayerData.collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `feePayerData.collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) external override { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `feePayerData.collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) external override onlyPool() notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); amountWithdrawn = positionData.withdraw( globalPositionData, collateralAmount, feePayerData ); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) external override onlyPool() notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { uint256 actualTime = getCurrentTime(); PositionData storage positionData = _getPositionData(msg.sender); positionData.requestWithdrawal( positionManagerData, collateralAmount, actualTime, feePayerData ); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external override onlyPool() notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { uint256 actualTime = getCurrentTime(); PositionData storage positionData = _getPositionData(msg.sender); amountWithdrawn = positionData.withdrawPassedRequest( globalPositionData, actualTime, feePayerData ); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external override onlyPool() notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); positionData.cancelWithdrawal(); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `feePayerData.collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create( FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens ) external override onlyPool() notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; positionData.create( globalPositionData, positionManagerData, collateralAmount, numTokens, feePayerData ); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `feePayerData.collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) external override onlyPool() notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); amountWithdrawn = positionData.redeeem( globalPositionData, positionManagerData, numTokens, feePayerData, msg.sender ); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `feePayerData.collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. */ function repay(FixedPoint.Unsigned memory numTokens) external override onlyPool() notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); positionData.repay(globalPositionData, positionManagerData, numTokens); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `feePayerData.collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external override onlyPool() isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = positions[msg.sender]; amountWithdrawn = positionData.settleEmergencyShutdown( globalPositionData, positionManagerData, feePayerData ); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override(IDerivativeMain, AdministrateeInterface) notEmergencyShutdown() nonReentrant() { require( msg.sender == positionManagerData.synthereumFinder.getImplementationAddress( SynthereumInterfaces.Manager ) || msg.sender == _getFinancialContractsAdminAddress(), 'Caller must be a Synthereum manager or the UMA governor' ); positionManagerData.emergencyShutdownTimestamp = getCurrentTime(); positionManagerData.requestOraclePrice( positionManagerData.emergencyShutdownTimestamp, feePayerData ); emit EmergencyShutdown( msg.sender, positionManagerData.emergencyShutdownTimestamp ); } /** @notice Remargin function */ function remargin() external override(IDerivativeMain, AdministrateeInterface) { return; } /** * @notice Drains any excess balance of the provided ERC20 token to a pre-selected beneficiary. * @dev This will drain down to the amount of tracked collateral and drain the full balance of any other token. * @param token address of the ERC20 token whose excess balance should be drained. */ function trimExcess(IERC20 token) external override nonReentrant() returns (FixedPoint.Unsigned memory amount) { FixedPoint.Unsigned memory pfcAmount = _pfc(); amount = positionManagerData.trimExcess(token, pfcAmount, feePayerData); } /** * @notice Delete a TokenSponsor position (This function can only be called by the contract itself) * @param sponsor address of the TokenSponsor. */ function deleteSponsorPosition(address sponsor) external onlyThisContract { delete positions[sponsor]; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view override nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { collateralAmount = positions[sponsor] .rawCollateral .getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier); } /** * @notice Get SynthereumFinder contract address * @return finder SynthereumFinder contract */ function synthereumFinder() external view override returns (ISynthereumFinder finder) { finder = positionManagerData.synthereumFinder; } /** * @notice Get synthetic token currency * @return token Synthetic token */ function tokenCurrency() external view override returns (IERC20 token) { token = positionManagerData.tokenCurrency; } /** * @notice Get synthetic token symbol * @return symbol Synthetic token symbol */ function syntheticTokenSymbol() external view override returns (string memory symbol) { symbol = IStandardERC20(address(positionManagerData.tokenCurrency)) .symbol(); } /** * @notice Get synthetic token price identifier registered with UMA DVM * @return identifier Synthetic token price identifier */ function priceIdentifier() external view override returns (bytes32 identifier) { identifier = positionManagerData.priceIdentifier; } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManagerPoolParty. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view override nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { totalCollateral = globalPositionData .rawTotalPositionCollateral .getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier); } /** * @notice Get the currently minted synthetic tokens from all derivatives * @return totalTokens Total amount of synthetic tokens minted */ function totalTokensOutstanding() external view override returns (FixedPoint.Unsigned memory totalTokens) { totalTokens = globalPositionData.totalTokensOutstanding; } /** * @notice Get the price of synthetic token set by DVM after emergencyShutdown call * @return Price of synthetic token */ function emergencyShutdownPrice() external view override isEmergencyShutdown() returns (FixedPoint.Unsigned memory) { return positionManagerData.emergencyShutdownPrice; } /** * @notice Accessor method for the list of members with admin role * @return array of addresses with admin role */ function getAdminMembers() external view override returns (address[] memory) { uint256 numberOfMembers = getRoleMemberCount(DEFAULT_ADMIN_ROLE); address[] memory members = new address[](numberOfMembers); for (uint256 j = 0; j < numberOfMembers; j++) { address newMember = getRoleMember(DEFAULT_ADMIN_ROLE, j); members[j] = newMember; } return members; } /** * @notice Accessor method for the list of members with pool role * @return array of addresses with pool role */ function getPoolMembers() external view override returns (address[] memory) { uint256 numberOfMembers = getRoleMemberCount(POOL_ROLE); address[] memory members = new address[](numberOfMembers); for (uint256 j = 0; j < numberOfMembers; j++) { address newMember = getRoleMember(POOL_ROLE, j); members[j] = newMember; } return members; } /** * @notice Transfers `collateralAmount` of `feePayerData.collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `feePayerData.collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo( address sponsor, FixedPoint.Unsigned memory collateralAmount ) public override onlyPool() notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { PositionData storage positionData = _getPositionData(sponsor); positionData.depositTo( globalPositionData, collateralAmount, feePayerData, sponsor ); } /** * @notice Get the collateralCurrency backing a synthetic token * @return collateral Collateral used for minting synthetic tokens */ function collateralCurrency() public view override(IDerivativeDeployment, FeePayerParty) returns (IERC20 collateral) { collateral = FeePayerParty.collateralCurrency(); } //---------------------------------------- // Internal functions //---------------------------------------- function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return globalPositionData.rawTotalPositionCollateral.getFeeAdjustedCollateral( feePayerData.cumulativeFeeMultiplier ); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface( feePayerData.finder.getImplementationAddress( OracleInterfaces.IdentifierWhitelist ) ); } function _getCollateralWhitelist() internal view returns (AddressWhitelistInterface) { return AddressWhitelistInterface( feePayerData.finder.getImplementationAddress( OracleInterfaces.CollateralWhitelist ) ); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. // These internal functions are supposed to act identically to modifiers, but re-used modifiers function _onlyCollateralizedPosition(address sponsor) internal view { require( positions[sponsor] .rawCollateral .getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier) .isGreaterThan(0), 'Position has no collateral' ); } function _notEmergencyShutdown() internal view { require( positionManagerData.emergencyShutdownTimestamp == 0, 'Contract emergency shutdown' ); } function _isEmergencyShutdown() internal view { require( positionManagerData.emergencyShutdownTimestamp != 0, 'Contract not emergency shutdown' ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require( _getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, 'Pending withdrawal' ); } function _getFinancialContractsAdminAddress() internal view returns (address) { return feePayerData.finder.getImplementationAddress( OracleInterfaces.FinancialContractsAdmin ); } }
Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `feePayerData.collateralCurrency`. Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral in order to account for precision loss. This contract must be approved to spend at least `numTokens` of `tokenCurrency`. This contract must have the Burner role for the `tokenCurrency`. numTokens is the number of tokens to be burnt for a commensurate amount of collateral. return amountWithdrawn The actual amount of collateral withdrawn./
function redeem(FixedPoint.Unsigned memory numTokens) external override onlyPool() notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); amountWithdrawn = positionData.redeeem( globalPositionData, positionManagerData, numTokens, feePayerData, msg.sender ); }
2,545,076
./partial_match/1/0x6893491CeCF9309e445fE10f49CEd15CBb08652F/sources/Migration_Schedar.sol
========== VIEWS ========== /
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](14); newAddresses[0] = CONTRACT_SYSTEMSTATUS; newAddresses[1] = CONTRACT_SYNTHETIXDEBTSHARE; newAddresses[2] = CONTRACT_FEEPOOLETERNALSTORAGE; newAddresses[3] = CONTRACT_EXCHANGER; newAddresses[4] = CONTRACT_ISSUER; newAddresses[5] = CONTRACT_REWARDESCROW_V2; newAddresses[6] = CONTRACT_DELEGATEAPPROVALS; newAddresses[7] = CONTRACT_REWARDSDISTRIBUTION; newAddresses[8] = CONTRACT_COLLATERALMANAGER; newAddresses[9] = CONTRACT_WRAPPER_FACTORY; newAddresses[10] = CONTRACT_ETHER_WRAPPER; newAddresses[11] = CONTRACT_EXT_AGGREGATOR_ISSUED_SYNTHS; newAddresses[12] = CONTRACT_EXT_AGGREGATOR_DEBT_RATIO; newAddresses[13] = CONTRACT_FUTURES_MARKET_MANAGER; addresses = combineArrays(existingAddresses, newAddresses); }
4,485,177
/** * @authors: [] * @reviewers: [] * @auditors: [] * @bounties: [] * @deployments: [] * * SPDX-License-Identifier: MIT */ pragma solidity >=0.7; import "./BinaryArbitrable.sol"; import "../.././interfaces/IAppealEvents.sol"; import "@kleros/erc-792/contracts/IArbitrable.sol"; import "@kleros/erc-792/contracts/IArbitrator.sol"; import "@kleros/erc-792/contracts/erc-1497/IEvidence.sol"; import "@kleros/ethereum-libraries/contracts/CappedMath.sol"; /** @title Linguo * @notice Linguo is a decentralized platform where anyone can submit a document for translation and have it translated by freelancers. * It has no platform fees and disputes about translation quality are handled by Kleros jurors. * @dev This contract trusts that the Arbitrator is honest and will not reenter or modify its costs during a call. * The arbitrator must support appeal periods. */ contract Linguo is IArbitrable, IEvidence, IAppealEvents { using CappedMath for uint256; using BinaryArbitrable for BinaryArbitrable.ArbitrableStorage; /* *** Contract variables *** */ uint8 public constant VERSION_ID = 0; // Value that represents the version of the contract. The value is incremented each time the new version is deployed. Range for LinguoETH: 0-127, LinguoToken: 128-255. uint256 public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. uint256 private constant NOT_PAYABLE_VALUE = (2**256 - 2) / 2; // A value depositors won't be able to pay. enum Status {Created, Assigned, AwaitingReview, DisputeCreated, Resolved} enum Party { None, // Party that is mapped with a 0 dispute ruling. Translator, // Party performing translation task. Challenger // Party challenging translated text in the review period. } // Arrays of 3 elements in the Task and Round structs map to the parties. Index "0" is not used, "1" is used for the translator and "2" for the challenger. struct Task { uint256 submissionTimeout; // Time in seconds allotted for submitting a translation. The end of this period is considered a deadline. uint256 minPrice; // Minimum price for the translation. When the task is created it has this minimum price that gradually increases such that it reaches the maximum price at the deadline. uint256 maxPrice; // Maximum price for the translation and also the value that must be deposited by the requester. Status status; // Status of the task. uint256 lastInteraction; // The time of the last action performed on the task. Note that lastInteraction is updated only during timeout-related actions such as the creation of the task and the submission of the translation. address payable requester; // The party requesting the translation. uint256 requesterDeposit; // The deposit requester makes when creating the task. Once the task is assigned this deposit will be partially reimbursed and its value replaced by the task price. uint256 sumDeposit; // The sum of the deposits of the translator and the challenger, if any. This value (minus arbitration fees) will be paid to the party that wins the dispute. address payable[3] parties; // Translator and challenger of the task. } address public governor = msg.sender; // The governor of the contract. uint256 public reviewTimeout; // Time in seconds, during which the submitted translation can be challenged. // All multipliers below are in basis points. uint256 public translationMultiplier; // Multiplier for calculating the value of the deposit translator must pay to self-assign a task. uint256 public challengeMultiplier; // Multiplier for calculating the value of the deposit challenger must pay to challenge a translation. Task[] public tasks; // Stores all created tasks. /// @dev Contains most of the data related to arbitration. BinaryArbitrable.ArbitrableStorage public arbitrableStorage; /* *** Events *** */ /** @dev To be emitted when a new task is created. * @param _taskID The ID of the newly created task. * @param _requester The address that created the task. * @param _timestamp When the task was created. */ event TaskCreated(uint256 indexed _taskID, address indexed _requester, uint256 _timestamp); /** @dev To be emitted when a translator assigns a task to himself. * @param _taskID The ID of the assigned task. * @param _translator The address that was assigned to the task. * @param _price The task price at the moment it was assigned. * @param _timestamp When the task was assigned. */ event TaskAssigned(uint256 indexed _taskID, address indexed _translator, uint256 _price, uint256 _timestamp); /** @dev To be emitted when a translation is submitted. * @param _taskID The ID of the respective task. * @param _translator The address that performed the translation. * @param _translatedText A URI to the translated text. * @param _timestamp When the translation was submitted. */ event TranslationSubmitted( uint256 indexed _taskID, address indexed _translator, string _translatedText, uint256 _timestamp ); /** @dev To be emitted when a translation is challenged. * @param _taskID The ID of the respective task. * @param _challenger The address of the challenger. * @param _timestamp When the task was challenged. */ event TranslationChallenged(uint256 indexed _taskID, address indexed _challenger, uint256 _timestamp); /** @dev To be emitted when a task is resolved, either by the translation being accepted, the requester being reimbursed or a dispute being settled. * @param _taskID The ID of the respective task. * @param _reason Short description of what caused the task to be solved. One of: 'translation-accepted' | 'requester-reimbursed' | 'dispute-settled' * @param _timestamp When the task was resolved. */ event TaskResolved(uint256 indexed _taskID, string _reason, uint256 _timestamp); /* *** Modifiers *** */ modifier onlyGovernor() { require(msg.sender == governor, "Only governor is allowed to perform this."); _; } /** @dev Constructor. * @param _arbitrator The arbitrator of the contract. * @param _arbitratorExtraData Extra data for the arbitrator. * @param _reviewTimeout Time in seconds during which a translation can be challenged. * @param _translationMultiplier Multiplier for calculating translator's deposit. In basis points. * @param _challengeMultiplier Multiplier for calculating challenger's deposit. In basis points. * @param _sharedStakeMultiplier Multiplier of the appeal cost that submitter must pay for a round when there is no winner/loser in the previous round. In basis points. * @param _winnerStakeMultiplier Multiplier of the appeal cost that the winner has to pay for a round. In basis points. * @param _loserStakeMultiplier Multiplier of the appeal cost that the loser has to pay for a round. In basis points. */ constructor( IArbitrator _arbitrator, bytes memory _arbitratorExtraData, uint256 _reviewTimeout, uint256 _translationMultiplier, uint256 _challengeMultiplier, uint256 _sharedStakeMultiplier, uint256 _winnerStakeMultiplier, uint256 _loserStakeMultiplier ) { reviewTimeout = _reviewTimeout; translationMultiplier = _translationMultiplier; challengeMultiplier = _challengeMultiplier; arbitrableStorage.setMultipliers(_sharedStakeMultiplier, _winnerStakeMultiplier, _loserStakeMultiplier); arbitrableStorage.setArbitrator(_arbitrator, _arbitratorExtraData); } // ******************** // // * Governance * // // ******************** // /** @dev Changes the governor of this contract. * @param _governor A new governor. */ function changeGovernor(address _governor) public onlyGovernor { governor = _governor; } /** @dev Changes the time allocated for the review phase. * @param _reviewTimeout A new value of the time allotted for reviewing a translation. In seconds. */ function changeReviewTimeout(uint256 _reviewTimeout) public onlyGovernor { reviewTimeout = _reviewTimeout; } /** @dev Changes the multiplier for translators' deposit. * @param _translationMultiplier A new value of the multiplier for calculating translator's deposit. In basis points. */ function changeTranslationMultiplier(uint256 _translationMultiplier) public onlyGovernor { translationMultiplier = _translationMultiplier; } /** @dev Changes the multiplier for challengers' deposit. * @param _challengeMultiplier A new value of the multiplier for calculating challenger's deposit. In basis points. */ function changeChallengeMultiplier(uint256 _challengeMultiplier) public onlyGovernor { challengeMultiplier = _challengeMultiplier; } /** @dev Changes the percentage of arbitration fees that must be paid by parties as a fee stake if there was no winner and loser in the previous round. * @param _sharedStakeMultiplier A new value of the multiplier of the appeal cost in case where there was no winner/loser in previous round. In basis point. */ function changeSharedStakeMultiplier(uint256 _sharedStakeMultiplier) public onlyGovernor { arbitrableStorage.setMultipliers( _sharedStakeMultiplier, arbitrableStorage.winnerStakeMultiplier, arbitrableStorage.loserStakeMultiplier ); } /** @dev Changes the percentage of arbitration fees that must be paid as a fee stake by the party that won the previous round. * @param _winnerStakeMultiplier A new value of the multiplier of the appeal cost that the winner of the previous round has to pay. In basis points. */ function changeWinnerStakeMultiplier(uint256 _winnerStakeMultiplier) public onlyGovernor { arbitrableStorage.setMultipliers( arbitrableStorage.sharedStakeMultiplier, _winnerStakeMultiplier, arbitrableStorage.loserStakeMultiplier ); } /** @dev Changes the percentage of arbitration fees that must be paid as a fee stake by the party that lost the previous round. * @param _loserStakeMultiplier A new value for the multiplier of the appeal cost that the party that lost the previous round has to pay. In basis points. */ function changeLoserStakeMultiplier(uint256 _loserStakeMultiplier) public onlyGovernor { arbitrableStorage.setMultipliers( arbitrableStorage.sharedStakeMultiplier, arbitrableStorage.winnerStakeMultiplier, _loserStakeMultiplier ); } // **************************** // // * Modifying the state * // // **************************** // /** @dev Creates a task based on provided details. Requires a value of maximum price to be deposited. * @param _deadline The deadline for the translation to be completed. * @param _minPrice A minimum price of the translation. In wei. * @param _metaEvidence A URI of a meta-evidence object for task submission. * @return taskID The ID of the created task. */ function createTask( uint256 _deadline, uint256 _minPrice, string calldata _metaEvidence ) external payable returns (uint256 taskID) { require(msg.value >= _minPrice, "Deposited value should be greater than or equal to the min price."); require(_deadline > block.timestamp, "The deadline should be in the future."); taskID = tasks.length; Task storage task = tasks.push(); task.submissionTimeout = _deadline - block.timestamp; task.minPrice = _minPrice; task.maxPrice = msg.value; task.lastInteraction = block.timestamp; task.requester = msg.sender; task.requesterDeposit = msg.value; emit MetaEvidence(taskID, _metaEvidence); emit TaskCreated(taskID, msg.sender, block.timestamp); } /** @dev Assigns a specific task to the sender. Requires a translator's deposit. * Note that the deposit should be a little higher than the required value because of the price increase during the time the transaction is mined. The surplus will be reimbursed. * @param _taskID The ID of the task. */ function assignTask(uint256 _taskID) external payable { Task storage task = tasks[_taskID]; require(block.timestamp - task.lastInteraction <= task.submissionTimeout, "The deadline has already passed."); uint256 price = task.minPrice + ((task.maxPrice - task.minPrice) * (block.timestamp - task.lastInteraction)) / task.submissionTimeout; uint256 arbitrationCost = arbitrableStorage.getArbitrationCost(); uint256 translatorDeposit = arbitrationCost.addCap((translationMultiplier.mulCap(price)) / MULTIPLIER_DIVISOR); require(task.status == Status.Created, "Task has already been assigned or reimbursed."); require(msg.value >= translatorDeposit, "Not enough ETH to reach the required deposit value."); task.parties[uint256(Party.Translator)] = msg.sender; task.status = Status.Assigned; uint256 remainder = task.maxPrice - price; task.requester.send(remainder); // Update requester's deposit since we reimbursed him the difference between maximum and actual price. task.requesterDeposit = price; task.sumDeposit = translatorDeposit; remainder = msg.value - translatorDeposit; msg.sender.send(remainder); emit TaskAssigned(_taskID, msg.sender, price, block.timestamp); } /** @dev Submits translated text for a specific task. * @param _taskID The ID of the task. * @param _translation A URI to the translated text. */ function submitTranslation(uint256 _taskID, string calldata _translation) external { Task storage task = tasks[_taskID]; require( task.status == Status.Assigned, "The task is either not assigned or translation has already been submitted." ); require(block.timestamp - task.lastInteraction <= task.submissionTimeout, "The deadline has already passed."); require( msg.sender == task.parties[uint256(Party.Translator)], "Can't submit translation to a task that wasn't assigned to you." ); task.status = Status.AwaitingReview; task.lastInteraction = block.timestamp; emit TranslationSubmitted(_taskID, msg.sender, _translation, block.timestamp); } /** @dev Reimburses the requester if no one picked the task or the translator failed to submit the translation before deadline. * @param _taskID The ID of the task. */ function reimburseRequester(uint256 _taskID) external { Task storage task = tasks[_taskID]; require(task.status < Status.AwaitingReview, "Can't reimburse if translation was submitted."); require( block.timestamp - task.lastInteraction > task.submissionTimeout, "Can't reimburse if the deadline hasn't passed yet." ); task.status = Status.Resolved; // Requester gets his deposit back and also the deposit of the translator, if there was one. // Note that sumDeposit can't contain challenger's deposit until the task is in DisputeCreated status. uint256 amount = task.requesterDeposit + task.sumDeposit; task.requester.send(amount); task.requesterDeposit = 0; task.sumDeposit = 0; emit TaskResolved(_taskID, "requester-reimbursed", block.timestamp); } /** @dev Pays the translator for completed task if no one challenged the translation during the review period. * @param _taskID The ID of the task. */ function acceptTranslation(uint256 _taskID) external { Task storage task = tasks[_taskID]; require(task.status == Status.AwaitingReview, "The task is in the wrong status."); require(block.timestamp - task.lastInteraction > reviewTimeout, "The review phase hasn't passed yet."); task.status = Status.Resolved; // Translator gets the price of the task and his deposit back. Note that sumDeposit can't contain challenger's deposit until the task has DisputeCreated status. uint256 amount = task.requesterDeposit + task.sumDeposit; task.parties[uint256(Party.Translator)].send(amount); task.requesterDeposit = 0; task.sumDeposit = 0; emit TaskResolved(_taskID, "translation-accepted", block.timestamp); } /** @dev Challenges the translation of a specific task. Requires challenger's deposit. * @param _taskID The ID of the task. * @param _evidence A link to evidence using its URI. Ignored if not provided. */ function challengeTranslation(uint256 _taskID, string calldata _evidence) external payable { Task storage task = tasks[_taskID]; uint256 arbitrationCost = arbitrableStorage.getArbitrationCost(); uint256 challengeDeposit = arbitrationCost.addCap( (challengeMultiplier.mulCap(task.requesterDeposit)) / MULTIPLIER_DIVISOR ); require(task.status == Status.AwaitingReview, "The task is in the wrong status."); require(block.timestamp - task.lastInteraction <= reviewTimeout, "The review phase has already passed."); require(msg.value >= challengeDeposit, "Not enough ETH to cover challenge deposit."); task.status = Status.DisputeCreated; task.parties[uint256(Party.Challenger)] = msg.sender; arbitrableStorage.createDispute(_taskID, arbitrationCost, _taskID, _taskID); task.sumDeposit = task.sumDeposit.addCap(challengeDeposit).subCap(arbitrationCost); uint256 remainder = msg.value - challengeDeposit; msg.sender.send(remainder); emit TranslationChallenged(_taskID, msg.sender, block.timestamp); arbitrableStorage.submitEvidence(_taskID, _taskID, _evidence); } /** @dev Takes up to the total amount required to fund a party of an appeal. Reimburses the rest. Creates an appeal if both parties are fully funded. * @param _taskID The ID of challenged task. * @param _ruling The party that pays the appeal fee. */ function fundAppeal(uint256 _taskID, uint256 _ruling) external payable { arbitrableStorage.fundAppeal(_taskID, _ruling); } /** @dev Withdraws contributions of appeal rounds. Reimburses contributions if no disputes were raised. If a dispute was raised, sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. * @param _beneficiary The address that made contributions. * @param _taskID The ID of the associated task. * @param _round The round from which to withdraw. */ function withdrawFeesAndRewards( address payable _beneficiary, uint256 _taskID, uint256 _round ) public { arbitrableStorage.withdrawFeesAndRewards(_taskID, _beneficiary, _round); } /** @dev Withdraws contributions of multiple appeal rounds at once. This function is O(n) where n is the number of rounds. This could exceed the gas limit, therefore this function should be used only as a utility and not be relied upon by other contracts. * @param _beneficiary The address that made contributions. * @param _taskID The ID of the associated task. * @param _cursor The round from where to start withdrawing. * @param _count The number of rounds to iterate. If set to 0 or a value larger than the number of rounds, iterates until the last round. */ function batchWithdrawFeesAndRewards( address payable _beneficiary, uint256 _taskID, uint256 _cursor, uint256 _count ) public { arbitrableStorage.batchWithdrawFeesAndRewards(_taskID, _beneficiary, _cursor, _count); } /** @dev Gives the ruling for a dispute. Can only be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract and to invert the ruling in the case a party loses from lack of appeal fees funding. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Refuse to arbitrate". */ function rule(uint256 _disputeID, uint256 _ruling) external override { Party finalRuling = Party(arbitrableStorage.processRuling(_disputeID, _ruling)); executeRuling(_disputeID, finalRuling); } /** @dev Executes the ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. */ function executeRuling(uint256 _disputeID, Party _finalRuling) internal { uint256 taskID = arbitrableStorage.externalIDtoLocalID[_disputeID]; Task storage task = tasks[taskID]; task.status = Status.Resolved; uint256 amount; if (_finalRuling == Party.None) { task.requester.send(task.requesterDeposit); // The value of sumDeposit is split among parties in this case. If the sum is uneven the value of 1 wei can be burnt. amount = task.sumDeposit / 2; task.parties[uint256(Party.Translator)].send(amount); task.parties[uint256(Party.Challenger)].send(amount); } else if (_finalRuling == Party.Translator) { amount = task.requesterDeposit + task.sumDeposit; task.parties[uint256(Party.Translator)].send(amount); } else { task.requester.send(task.requesterDeposit); task.parties[uint256(Party.Challenger)].send(task.sumDeposit); } task.requesterDeposit = 0; task.sumDeposit = 0; emit TaskResolved(taskID, "dispute-settled", block.timestamp); } /** @dev Submit a reference to evidence. EVENT. * @param _taskID The ID of the task. * @param _evidence A link to evidence using its URI. */ function submitEvidence(uint256 _taskID, string calldata _evidence) external { arbitrableStorage.submitEvidence(_taskID, _taskID, _evidence); } // ******************** // // * Getters * // // ******************** // /** @dev Returns the sum of withdrawable wei from appeal rounds. * This function is O(n), where n is the number of rounds of the task. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * Beware that withdrawals are allowed only after the dispute gets Resolved. * @param _taskID The ID of the associated task. * @param _beneficiary The contributor for which to query. * @return total The total amount of wei available to withdraw. */ function getTotalWithdrawableAmount(uint256 _taskID, address _beneficiary) external view returns (uint256 total) { uint256 totalRounds = arbitrableStorage.disputes[_taskID].roundCounter; for (uint256 roundI; roundI < totalRounds; roundI++) { (uint256 rewardA, uint256 rewardB) = arbitrableStorage.getWithdrawableAmount(_taskID, _beneficiary, roundI); total += rewardA + rewardB; } } /** @dev Gets the deposit required for self-assigning the task. * @param _taskID The ID of the task. * @return deposit The translator's deposit. */ function getDepositValue(uint256 _taskID) public view returns (uint256 deposit) { Task storage task = tasks[_taskID]; if (block.timestamp - task.lastInteraction > task.submissionTimeout || task.status != Status.Created) { deposit = NOT_PAYABLE_VALUE; } else { uint256 price = task.minPrice + ((task.maxPrice - task.minPrice) * (block.timestamp - task.lastInteraction)) / task.submissionTimeout; uint256 arbitrationCost = arbitrableStorage.getArbitrationCost(); deposit = arbitrationCost.addCap((translationMultiplier.mulCap(price)) / MULTIPLIER_DIVISOR); } } /** @dev Gets the deposit required for challenging the translation. * @param _taskID The ID of the task. * @return deposit The challengers's deposit. */ function getChallengeValue(uint256 _taskID) public view returns (uint256 deposit) { Task storage task = tasks[_taskID]; if (block.timestamp - task.lastInteraction > reviewTimeout || task.status != Status.AwaitingReview) { deposit = NOT_PAYABLE_VALUE; } else { uint256 arbitrationCost = arbitrableStorage.getArbitrationCost(); deposit = arbitrationCost.addCap((challengeMultiplier.mulCap(task.requesterDeposit)) / MULTIPLIER_DIVISOR); } } /** @dev Gets the current price of a specified task. * @param _taskID The ID of the task. * @return price The price of the task. */ function getTaskPrice(uint256 _taskID) public view returns (uint256 price) { Task storage task = tasks[_taskID]; if (block.timestamp - task.lastInteraction > task.submissionTimeout || task.status != Status.Created) { price = 0; } else { price = task.minPrice + ((task.maxPrice - task.minPrice) * (block.timestamp - task.lastInteraction)) / task.submissionTimeout; } } /** @dev Gets the total number of created tasks. * @return The number of created tasks. */ function getTaskCount() public view returns (uint256) { return tasks.length; } /** @dev Gets the number of rounds of the specific task. * @param _taskID The ID of the task. * @return The number of rounds. */ function getNumberOfRounds(uint256 _taskID) public view returns (uint256) { return arbitrableStorage.getNumberOfRounds(_taskID); } /** @dev Gets the contributions made by a party for a given round of appeal of a task. * @param _taskID The ID of the task. * @param _round The position of the round. * @param _contributor The address of the contributor. * @return contributions The contributions. */ function getContributions( uint256 _taskID, uint256 _round, address _contributor ) public view returns (uint256[3] memory contributions) { return arbitrableStorage.getContributions(_taskID, _round, _contributor); } /** @dev Gets the addresses of parties of a specified task. * @param _taskID The ID of the task. * @return parties The addresses of translator and challenger as [ZERO_ADDRESS, translator, challenger]. */ function getTaskParties(uint256 _taskID) public view returns (address payable[3] memory parties) { Task storage task = tasks[_taskID]; parties = task.parties; } /** @dev Gets the information on a round of a task. * @param _taskID The ID of the task. * @param _round The round to be queried. * @return paidFees rulingFunded feeRewards appealed The round information. */ function getRoundInfo(uint256 _taskID, uint256 _round) public view returns ( uint256[3] memory paidFees, uint256 rulingFunded, uint256 feeRewards, bool appealed ) { return arbitrableStorage.getRoundInfo(_taskID, _round); } }
Changes the percentage of arbitration fees that must be paid by parties as a fee stake if there was no winner and loser in the previous round. _sharedStakeMultiplier A new value of the multiplier of the appeal cost in case where there was no winner/loser in previous round. In basis point./
function changeSharedStakeMultiplier(uint256 _sharedStakeMultiplier) public onlyGovernor { arbitrableStorage.setMultipliers( _sharedStakeMultiplier, arbitrableStorage.winnerStakeMultiplier, arbitrableStorage.loserStakeMultiplier ); }
913,290
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /******************************************************************************* * * Copyright (c) 2018-2022 Modenero Corp. * Released under the MIT License. * * ServiceName - Service description. * * Version YY.MM.DD * * https://modenero.com * [email protected] */ /******************************************************************************* * * SafeMath */ library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } /******************************************************************************* * * ECRecovery * * Contract function to validate signature of pre-approved token transfers. * (borrowed from LavaWallet) */ interface ECRecovery { function recover(bytes32 hash, bytes memory sig) external pure returns (address); } /******************************************************************************* * * ERC Token Standard #20 Interface * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ interface ERC20Interface { function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /******************************************************************************* * * ApproveAndCallFallBack * * Contract function to receive approval and execute function in one call * (borrowed from MiniMeToken) */ interface ApproveAndCallFallBack { function approveAndCall(address spender, uint tokens, bytes memory data) external; function receiveApproval(address from, uint256 tokens, address token, bytes memory data) external; } /******************************************************************************* * * Owned contract */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /******************************************************************************* * * ModeneroDb Interface */ interface ModeneroDbInterface { /* Interface getters. */ function getAddress(bytes32 _key) external view returns (address); function getBool(bytes32 _key) external view returns (bool); function getBytes(bytes32 _key) external view returns (bytes memory); function getInt(bytes32 _key) external view returns (int); function getString(bytes32 _key) external view returns (string memory); function getUint(bytes32 _key) external view returns (uint); /* Interface setters. */ function setAddress(bytes32 _key, address _value) external; function setBool(bytes32 _key, bool _value) external; function setBytes(bytes32 _key, bytes calldata _value) external; function setInt(bytes32 _key, int _value) external; function setString(bytes32 _key, string calldata _value) external; function setUint(bytes32 _key, uint _value) external; /* Interface deletes. */ function deleteAddress(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteUint(bytes32 _key) external; } /******************************************************************************* * * @notice Service Name * * @dev Developer details. */ contract ServiceName is Owned { using SafeMath for uint; /* Initialize predecessor contract. */ address private _predecessor; /* Initialize successor contract. */ address private _successor; /* Initialize revision number. */ uint private _revision; /* Initialize Modenero Db contract. */ ModeneroDbInterface private _modeneroDb; /** * @dev * * Set Namespace * * Provides a "unique" name for generating "unique" data identifiers, * most commonly used as database "key-value" keys. * * NOTE: Use of `namespace` is REQUIRED when generating ANY & ALL * ModeneroDb keys; in order to prevent ANY accidental or * malicious SQL-injection vulnerabilities / attacks. */ string private _namespace = 'SERVICE_NAME_HERE'; event Broadcast( address indexed primary, address secondary, bytes data ); /*************************************************************************** * * Constructor */ constructor() { /* Initialize ModeneroDb (eternal) storage database contract. */ // NOTE We hard-code the address here, since it should never change. // _modeneroDb = ModeneroDbInterface(0x68133E0A4996D0103c2135dcD8E2084450DF66D5); // Avalanche | AVAX // _modeneroDb = ModeneroDbInterface(0x7AaCEC83e10D8F8DfDfaa4858d55b0cC29eE4795); // Binance Smart Chain | BSC // _modeneroDb = ModeneroDbInterface(0x0B79d476DaC963Bf4D342233AB129Ab833077627); // Ethereum | ETH // _modeneroDb = ModeneroDbInterface(0x7AaCEC83e10D8F8DfDfaa4858d55b0cC29eE4795); // Fantom | FTM // _modeneroDb = ModeneroDbInterface(0xeF54AE01D55ADeCac852cBe3e6F16b0D1bf38dE0); // Polygon | MATIC /* Initialize (aname) hash. */ bytes32 hash = keccak256(abi.encodePacked('aname.', _namespace)); /* Set predecessor address. */ _predecessor = _modeneroDb.getAddress(hash); /* Verify predecessor address. */ if (_predecessor != address(0x0)) { /* Make address payable. */ address payable predecessor = payable(address(uint160(_predecessor))); /* Retrieve the last revision number (if available). */ uint lastRevision = ServiceName(predecessor).getRevision(); /* Set (current) revision number. */ _revision = lastRevision + 1; } } /** * @dev Only allow access to an authorized Modenero administrator. */ modifier onlyAuthByModenero() { /* Verify write access is only permitted to authorized accounts. */ require(_modeneroDb.getBool(keccak256( abi.encodePacked(msg.sender, '.has.auth.for.', _namespace))) == true); _; // function code is inserted here } /** * THIS CONTRACT DOES NOT ACCEPT DIRECT PAYMENTS */ fallback () external payable { /* Cancel this transaction. */ revert('Oops! Direct payments are NOT permitted here.'); } receive () external payable { /* Cancel this transaction. */ revert('Oops! Direct payments are NOT permitted here.'); } /*************************************************************************** * * ACTIONS * */ function firstAction() public pure returns(bool) { // TODO /* Return success. */ return true; } /*************************************************************************** * * GETTERS * */ /** * Get Revision (Number) */ function getRevision() public view returns (uint) { return _revision; } /** * Get Predecessor (Address) */ function getPredecessor() public view returns (address) { return _predecessor; } /** * Get Successor (Address) */ function getSuccessor() public view returns (address) { return _successor; } /*************************************************************************** * * SETTERS * */ /** * Set Successor * * This is the contract address that replaced this current instnace. */ function setSuccessor( address _newSuccessor ) onlyAuthByModenero external returns (bool success) { /* Set successor contract. */ _successor = _newSuccessor; /* Return success. */ return true; } /*************************************************************************** * * INTERFACES * */ /** * Supports Interface (EIP-165) * * (see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md) * * NOTE: Must support the following conditions: * 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface) * 2. (false) when interfaceID is 0xffffffff * 3. (true) for any other interfaceID this contract implements * 4. (false) for any other interfaceID */ function supportsInterface( bytes4 _interfaceID ) external pure returns (bool) { /* Initialize constants. */ bytes4 InvalidId = 0xffffffff; bytes4 ERC165Id = 0x01ffc9a7; /* Validate condition #2. */ if (_interfaceID == InvalidId) { return false; } /* Validate condition #1. */ if (_interfaceID == ERC165Id) { return true; } // TODO Add additional interfaces here. /* Return false (for condition #4). */ return false; } /** * ECRecovery Interface */ function _ecRecovery() private view returns ( ECRecovery ecrecovery ) { /* Initialize hash. */ bytes32 hash = keccak256('aname.ecrecovery'); /* Retrieve value from Modenero Db. */ address aname = _modeneroDb.getAddress(hash); /* Initialize interface. */ ecrecovery = ECRecovery(aname); } /*************************************************************************** * * UTILITIES * */ /** * Is (Owner) Contract * * Tests if a specified account / address is a contract. */ function _ownerIsContract( address _owner ) private view returns (bool isContract) { /* Initialize code length. */ uint codeLength; /* Run assembly. */ assembly { /* Retrieve the size of the code on target address. */ codeLength := extcodesize(_owner) } /* Set test result. */ isContract = (codeLength > 0); } /** * Bytes-to-Address * * Converts bytes into type address. */ function _bytesToAddress( bytes memory _address ) private pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; // b = uint160(_address[i]); // NOTE: This line broke in v0.5.0 b = uint160(uint8(_address[i])); // NOTE: This HAS NOT been tested yet. m += (b); } return address(m); } /** * Convert Bytes to Bytes32 */ function _bytesToBytes32( bytes memory _data, uint _offset ) private pure returns (bytes32 result) { /* Loop through each byte. */ for (uint i = 0; i < 32; i++) { /* Shift bytes onto result. */ result |= bytes32(_data[i + _offset] & 0xFF) >> (i * 8); } } /** * Convert Bytes32 to Bytes * * NOTE: Since solidity v0.4.22, you can use `abi.encodePacked()` for this, * which returns bytes. (https://ethereum.stackexchange.com/a/55963) */ function _bytes32ToBytes( bytes32 _data ) private pure returns (bytes memory result) { /* Pack the data. */ return abi.encodePacked(_data); } }
Bytes-to-Address Converts bytes into type address./ b = uint160(_address[i]); NOTE: This line broke in v0.5.0
function _bytesToAddress( bytes memory _address ) private pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; m += (b); } return address(m); }
922,248
./full_match/11155111/0x96383063Fe5c012fe2C5CF6524f9DE700Cd905de/sources/project_/contracts/Vehicle.sol
The vehicle owner is given the ability to modify the URI with the documentation if there are any errors discovered.
function setNewDocumentationURI( string calldata newDocumentationURI ) external virtual override onlyVehicleOwner isActive { require( keccak256(abi.encodePacked(newDocumentationURI)) != keccak256(abi.encodePacked('')), 'please pass a valid documentation URI' ); require( keccak256(abi.encodePacked(newDocumentationURI)) != keccak256(abi.encodePacked(documentationURI)), 'the new URI must be different from the existing documentation URI' ); documentationURI = newDocumentationURI; }
3,788,765
// SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "../interfaces/IPayment.sol"; import "../libraries/LibDiamond.sol"; import "../libraries/LibPayment.sol"; contract PaymentFacet is IPayment { /// @notice Adds/removes a payment token /// @param _token The target token /// @param _status Whether the token will be added or removed function setPaymentToken(address _token, bool _status) external override { require(_token != address(0), "PaymentFacet: _token must not be 0x0"); LibDiamond.enforceIsContractOwner(); LibPayment.updatePaymentToken(_token, _status); emit SetPaymentToken(_token, _status); } /// @notice Gets whether the payment token is supported /// @param _token The target token function supportsPaymentToken(address _token) external view override returns (bool) { return LibPayment.containsPaymentToken(_token); } /// @notice Gets the total amount of token payments function totalPaymentTokens() external view override returns (uint256) { return LibPayment.tokensCount(); } /// @notice Gets the payment token at a given index /// @param _index The token index function paymentTokenAt(uint256 _index) external view override returns (address) { return LibPayment.tokenAt(_index); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IPayment { /// @notice An event emitted once a payment token is set event SetPaymentToken(address _token, bool _status); /// @notice Adds/removes a payment token /// @param _token The target token /// @param _status Whether the token will be added or removed function setPaymentToken(address _token, bool _status) external; /// @notice Gets whether the payment token is supported /// @param _token The target token function supportsPaymentToken(address _token) external view returns (bool); /// @notice Gets the total amount of token payments function totalPaymentTokens() external view returns (uint256); /// @notice Gets the payment token at a given index /// @param _index The token index function paymentTokenAt(uint256 _index) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "../interfaces/IDiamondCut.sol"; library LibDiamond { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); struct FacetAddressAndPosition { address facetAddress; uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint16 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the selector in the facetFunctionSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); function setContractOwner(address _newOwner) internal { DiamondStorage storage ds = diamondStorage(); address previousOwner = ds.contractOwner; ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = diamondStorage().contractOwner; } function enforceIsContractOwner() internal view { require( msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner" ); } event DiamondCut( IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata ); // Internal function version of diamondCut function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { for ( uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++ ) { IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action; if (action == IDiamondCut.FacetCutAction.Add) { addFunctions( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors ); } else if (action == IDiamondCut.FacetCutAction.Replace) { replaceFunctions( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors ); } else if (action == IDiamondCut.FacetCutAction.Remove) { removeFunctions( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors ); } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addFunctions( address _facetAddress, bytes4[] memory _functionSelectors ) internal { require( _functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut" ); DiamondStorage storage ds = diamondStorage(); // uint16 selectorCount = uint16(diamondStorage().selectors.length); require( _facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)" ); uint16 selectorPosition = uint16( ds.facetFunctionSelectors[_facetAddress].functionSelectors.length ); // add new facet address if it does not exist if (selectorPosition == 0) { enforceHasContractCode( _facetAddress, "LibDiamondCut: New facet has no code" ); ds .facetFunctionSelectors[_facetAddress] .facetAddressPosition = uint16(ds.facetAddresses.length); ds.facetAddresses.push(_facetAddress); } for ( uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++ ) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds .selectorToFacetAndPosition[selector] .facetAddress; require( oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists" ); addFunction(ds, selector, selectorPosition, _facetAddress); selectorPosition++; } } function replaceFunctions( address _facetAddress, bytes4[] memory _functionSelectors ) internal { require( _functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut" ); DiamondStorage storage ds = diamondStorage(); require( _facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)" ); uint16 selectorPosition = uint16( ds.facetFunctionSelectors[_facetAddress].functionSelectors.length ); // add new facet address if it does not exist if (selectorPosition == 0) { enforceHasContractCode( _facetAddress, "LibDiamondCut: New facet has no code" ); ds .facetFunctionSelectors[_facetAddress] .facetAddressPosition = uint16(ds.facetAddresses.length); ds.facetAddresses.push(_facetAddress); } for ( uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++ ) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds .selectorToFacetAndPosition[selector] .facetAddress; require( oldFacetAddress != _facetAddress, "LibDiamondCut: Can't replace function with same function" ); removeFunction(ds, oldFacetAddress, selector); // add function addFunction(ds, selector, selectorPosition, _facetAddress); selectorPosition++; } } function removeFunctions( address _facetAddress, bytes4[] memory _functionSelectors ) internal { require( _functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut" ); DiamondStorage storage ds = diamondStorage(); // if function does not exist then do nothing and return require( _facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)" ); for ( uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++ ) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds .selectorToFacetAndPosition[selector] .facetAddress; removeFunction(ds, oldFacetAddress, selector); } } function addFunction( DiamondStorage storage ds, bytes4 _selector, uint16 _selectorPosition, address _facetAddress ) internal { ds .selectorToFacetAndPosition[_selector] .functionSelectorPosition = _selectorPosition; ds.facetFunctionSelectors[_facetAddress].functionSelectors.push( _selector ); ds.selectorToFacetAndPosition[_selector].facetAddress = _facetAddress; } function removeFunction( DiamondStorage storage ds, address _facetAddress, bytes4 _selector ) internal { require( _facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist" ); // an immutable function is a function defined directly in a diamond require( _facetAddress != address(this), "LibDiamondCut: Can't remove immutable function" ); // replace selector with last selector, then delete last selector uint256 selectorPosition = ds .selectorToFacetAndPosition[_selector] .functionSelectorPosition; uint256 lastSelectorPosition = ds .facetFunctionSelectors[_facetAddress] .functionSelectors .length - 1; // if not the same then replace _selector with lastSelector if (selectorPosition != lastSelectorPosition) { bytes4 lastSelector = ds .facetFunctionSelectors[_facetAddress] .functionSelectors[lastSelectorPosition]; ds.facetFunctionSelectors[_facetAddress].functionSelectors[ selectorPosition ] = lastSelector; ds .selectorToFacetAndPosition[lastSelector] .functionSelectorPosition = uint16(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; uint256 facetAddressPosition = ds .facetFunctionSelectors[_facetAddress] .facetAddressPosition; if (facetAddressPosition != lastFacetAddressPosition) { address lastFacetAddress = ds.facetAddresses[ lastFacetAddressPosition ]; ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds .facetFunctionSelectors[lastFacetAddress] .facetAddressPosition = uint16(facetAddressPosition); } ds.facetAddresses.pop(); delete ds .facetFunctionSelectors[_facetAddress] .facetAddressPosition; } } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require( _calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty" ); } else { require( _calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)" ); if (_init != address(this)) { enforceHasContractCode( _init, "LibDiamondCut: _init address has no code" ); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function enforceHasContractCode( address _contract, string memory _errorMessage ) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; // Stores information about Payment Tokens library LibPayment { using EnumerableSet for EnumerableSet.AddressSet; bytes32 constant PAYMENT_STORAGE_POSITION = keccak256("payment.storage"); struct PaymentStorage { // Stores all supported tokens as payments for ERC-721 EnumerableSet.AddressSet tokens; } function paymentStorage() internal pure returns (PaymentStorage storage ps) { bytes32 position = PAYMENT_STORAGE_POSITION; assembly { ps.slot := position } } /// @notice Returns the count of payment tokens function tokensCount() internal view returns (uint256) { PaymentStorage storage ps = paymentStorage(); return ps.tokens.length(); } /// @notice Returns the address of the payment token at a given index function tokenAt(uint256 _index) internal view returns (address) { PaymentStorage storage ps = paymentStorage(); return ps.tokens.at(_index); } function updatePaymentToken(address _paymentToken, bool _status) internal { PaymentStorage storage ps = paymentStorage(); if (_status) { require( ps.tokens.add(_paymentToken), "LibPayment: payment token already added" ); } else { require( ps.tokens.remove(_paymentToken), "LibPayment: payment token not found" ); } } /// @notice Returns true/false depending on whether a given payment token is found function containsPaymentToken(address _token) internal view returns (bool) { PaymentStorage storage ps = paymentStorage(); return ps.tokens.contains(_token); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IDiamondCut { enum FacetCutAction { Add, Replace, Remove } // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); } // 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]; } // 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)); } }
Gets the payment token at a given index _index The token index
function paymentTokenAt(uint256 _index) external view override returns (address) { return LibPayment.tokenAt(_index); }
1,334,777
./full_match/3/0x93d137764C7f7C339B7a3F7AeF6f03bfceb725a0/sources/home/mitgen/Private_Projects/DeFi/poolRegistry/contracts/interface/IPool.sol
Deposits Withdrawals GET INFO SET NEW VALUE
interface IPool { event PoolDeposit( address indexed _from, address indexed _tokenAddress, uint256 _amount, uint256 lock_period ); event DepositRequest( address indexed _lpAddress, address indexed _tokenAddress, bytes32 indexed _id, uint256 _maxValue ); event PoolFundingRequestApproved( address indexed _lpAddress, address indexed _tokenAddress, bytes32 indexed _id, uint256 value ); event PoolFundingRequestDenied( address indexed _lpAddress, address indexed _tokenAddress, bytes32 indexed _id, uint256 _maxValue ); event PoolWithdrawalRequestCreated( address indexed _from, bytes32 indexed _id, address indexed tokenAddress, uint256 _amount ); event PoolWithdrawalRequestApproved( address indexed _from, bytes32 indexed _id, address indexed tokenAddress, uint256 _value ); event PoolWithdrawalRequestDenied( address indexed _from, bytes32 indexed _id, address indexed tokenAddress, uint256 _value ); event WithdrawalRequestCompleted( address indexed _from, bytes32 indexed _id, address indexed tokenAddress, uint256 _value ); event Lock( address indexed sender, uint256 indexed index, bytes32 indexed details ); event ReleaseEthToContributer( uint8 indexed role, address indexed addr, uint256 value ); event ReleaseEther(address indexed addr, uint256 value); event ReleaseToken(address indexed addr, uint256 value); function hasRole(bytes32 role, address account) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function token() external view returns (address); function locked() external view returns (uint256); function rate() external view returns (uint256); function interestFee() external view returns (uint256); function anualPrecent() external view returns (uint256); function getDepositEther(address owner, uint256 index) external view returns(address investor, uint256 amount, uint256 time, uint256 lock_period, bool refund_authorize); function getDepositToken(address owner, uint256 index) external view returns(address investor, address tokenAddress, uint256 amount, uint256 time, uint256 lock_period, bool refund_authorize); function setToken(address tokenAddress) external returns (bool); function setLock(uint256 lock) external returns (bool); function setRate(uint256 newRate) external returns (bool); function setInterestFee(uint256 fee) external returns (bool); function setAnnualPrecent(uint256 precent) external returns (bool); function depositEther(address sender) external payable returns (bool); function depositToken(address sender, uint256 amount) external returns (bool); function _depositEtherInternal(address sender, uint256 amount) external returns (bool); }
8,094,112
./partial_match/3/0x6cc9b43f81C40E3BB3Fe544472F2653EE539E75C/sources/MyLotto.sol
get total sale amount for all sale session/
function getTotalSaleAmountForAllSale() external view returns(uint256){ return totalSaleAmountForAllSales; }
5,278,813
pragma solidity >=0.5.0 <0.6.0; // this is a rock-paper-scissors tournament // players join, compete against one another until the tournament winner is declared // players must commit their answers before revealing them // there are time limits for each round // after each tournament, a new one is automatically created; owner can change parameters contract Game { // global position variable; used when players are joining uint position; // current game variables uint players; // amount of wins needed to win tournament (rounds) is linked to amount of players in tournament // e.g. if there are 16 players, player must win 4 games to win tournament uint rounds; // amount of time for players have each round to play, otherwise they automaticaly lose uint time; // entry fee for tournament; is distributed at end of tournament uint fee; // new game variables that take effect in the next tournament uint nPlayers; uint nRounds; uint nTime; uint nFee; address payable owner; // array holds all time limits uint[] public times; // mapping for storing hashes; players must hash their address, their sign (rock, paper or scissors = 1, 2 or 3) (uint) // and their secret (string variable) mapping (address => bytes32) commitments; // data structures // addresses maps to structs, addresses are stored in array mapping (address => player) public mPlayers; // array doesn't change size once all players have joined // instead, players are rearranged as tournament progresses // algoritim determines players' opponents as well as their new positions (if they win) address payable[] aPlayers; struct player { uint position; uint round; uint sign; bool commit; } // names owner and creates genisis tournament constructor() public { owner = msg.sender; nPlayers = 2; nRounds = 1; nTime = 3600; nFee = 0; advance(); } modifier authority() { require(msg.sender == owner); _; } // allows owner to change tournament parameters (for next tournament) function update(uint _players, uint _rounds, uint _time, uint _fee) public authority { nPlayers = _players; nRounds = _rounds; nTime = _time; nFee = _fee; } // requires tournament to have room to join, players must have not joined beforehand // Ether sent must be correct amount modifier space() { require(position < players && mPlayers[msg.sender].position == 0 && msg.value == fee); _; } function join() public payable space { // players are assigned a position position++; mPlayers[msg.sender].position = position; // are added into the array (based on their position) aPlayers.push(msg.sender); // once all players have joined the tournament, time limits for all rounds are assigned if (position == players) { for (uint i = 1; i <= rounds; i++) { // if time limits are 60 seconds, time limit for round two will be 60 * 2 + now (current time) times.push(time * i + now); } } } // if player's position is zero, they are disqualified // can only commit once and must be within time limit for their round modifier ready() { require(mPlayers[msg.sender].position != 0 && mPlayers[msg.sender].commit == false && times[mPlayers[msg.sender].round] > now); _; } // stores hash, updates player's struct function commit(bytes32 _commitment) public ready { commitments[msg.sender] = _commitment; mPlayers[msg.sender].commit = true; } // must have committed modifier right() { require(mPlayers[msg.sender].commit == true); _; } // commit and reveal scheme: // player must send sign and secret, address is obtained through msg.sender // thus players cannot copy another player's hash; must be unique as player cannot fake having an address of another player function play(uint _sign, string memory _secret) public right { // must be one of three possibilities (rock, paper or scissors) if (_sign == 1 || _sign == 2 || _sign == 3) { // finds opponent address payable adversary = find(msg.sender); // if opponent has committed and answer matches with hash, player's sign is stored if (mPlayers[adversary].commit == true && keccak256(abi.encodePacked(msg.sender, _sign, _secret)) == commitments[msg.sender]) { mPlayers[msg.sender].sign = _sign; // if opponent has already played, the outcome of the game is determined if (mPlayers[adversary].sign != 0) { // determines the winner of the rock-paper-scissors game uint result = who(_sign, mPlayers[adversary].sign); // tie game, players' signs (and commits) are reset (allowing them to play again) if (result == 0) { mPlayers[msg.sender].sign = 0; mPlayers[msg.sender].commit = false; mPlayers[adversary].sign = 0; mPlayers[adversary].commit = false; // player wins } else if (result == 1) { update(msg.sender, adversary); // opponent wins } else { update(adversary, msg.sender); } } } } } // ensures time limit has passed modifier honest() { require(times[mPlayers[msg.sender].round] < now); _; } // if player's opponent has yet to commit or play, and the player has, they win automatically function automatic() public honest { address payable adversary = find(msg.sender); // player has committed, opponent has not if (mPlayers[adversary].commit == false && mPlayers[msg.sender].commit == true) { update(msg.sender, adversary); // player has played, opponent has not } else if (mPlayers[adversary].sign == 0 && mPlayers[msg.sender].sign != 0) { update(msg.sender, adversary); } } // advances the winner, disqualifies the loser function update(address payable _winner, address payable _loser) internal { // variables for determining whether player position is even or odd // from this their new position is determined uint x = mPlayers[_winner].position; uint y = mPlayers[_winner].round; uint z = (x - 1) / 2 ** y + 1; mPlayers[_winner].round++; // if player has won the tournament, the player receives the prize, the tournament is cleared // and a new tournament is created if (mPlayers[_winner].round == rounds) { // can change the distribution of the prize (e.g. owner takes 25% cut) _winner.transfer(fee * players); clear(); advance(); } else { // player's position only changes if it is even, otherwise it stays the same if (z % 2 == 0) { mPlayers[_winner].position = x - 2 ** y; // must subtract one from position because arrays start from zero aPlayers[(x - 2 ** y) - 1] = _winner; } // player's sign and commit is reset mPlayers[_winner].sign = 0; mPlayers[_winner].commit = false; // loser is disqualified mPlayers[_loser].position = 0; } } // for finding player's opponent, receives player's address and returns opponent's address function find(address payable _player) internal view returns (address payable) { // same as above: used to determine whether player's position is even or odd uint x = mPlayers[_player].position; uint y = mPlayers[_player].round; uint z = (x - 1) / 2 ** y + 1; uint opponent; // even number, opponent's position is 2 ** y (player's round) less than player's position if (z % 2 == 0) { // subtract one for array opponent = (x - 2 ** y) - 1; // odd number, opponent's position is 2 ** y more } else { opponent = (x + 2 ** y) - 1; } // opponent must be in same round as player if (mPlayers[aPlayers[opponent]].round == y) { return aPlayers[opponent]; } } // clears all relevant arrays and mappings for new tournament function clear() internal { // for deleting mapping, iteration is required for (uint i = 0; i < aPlayers.length; i++) { delete mPlayers[aPlayers[i]]; } delete aPlayers; delete times; } // creates the new tournament, is automatically called at the end of a tournament function advance() internal { // n variables remain the same, unless owner has changed them // if so, new tournament will run with new variables players = nPlayers; rounds = nRounds; time = nTime; fee = nFee; // global variable is reset position = 0; } // logic for determining winner of rock-paper-scissors game // e.g. 1 beats 3 or rock beats scissors function who(uint _one, uint _two) internal pure returns (uint) { if (_one == 1 && _two == 1) { return 0; } else if (_one == 1 && _two == 2) { return 2; } else if (_one == 1 && _two == 3) { return 1; } else if (_one == 2 && _two == 1) { return 1; } else if (_one == 2 && _two == 2) { return 0; } else if (_one == 2 && _two == 3) { return 2; } else if (_one == 3 && _two == 1) { return 2; } else if (_one == 3 && _two == 2) { return 1; } else if (_one == 3 && _two == 3) { return 0; } } }
for finding player's opponent, receives player's address and returns opponent's address same as above: used to determine whether player's position is even or odd even number, opponent's position is 2 y (player's round) less than player's position subtract one for array odd number, opponent's position is 2 y more opponent must be in same round as player
function find(address payable _player) internal view returns (address payable) { uint x = mPlayers[_player].position; uint y = mPlayers[_player].round; uint z = (x - 1) / 2 ** y + 1; uint opponent; if (z % 2 == 0) { opponent = (x - 2 ** y) - 1; opponent = (x + 2 ** y) - 1; } if (mPlayers[aPlayers[opponent]].round == y) { return aPlayers[opponent]; } }
15,871,371
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol
Reads the uint184 at `cdPtr` in calldata.
function readUint184( CalldataPointer cdPtr ) internal pure returns (uint184 value) { assembly ("memory-safe") { value := calldataload(cdPtr) } }
8,451,715
pragma solidity ^0.4.21; /// @title SafeMath contract - Math operations with safety checks. /// @author OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol contract SafeMath { function mulsm(uint256 a, uint256 b) internal pure returns (uint256) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function divsm(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function subsm(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function addsm(uint256 a, uint256 b) internal pure returns (uint256) { uint c = a + b; assert(c >= a); return c; } function powsm(uint256 a, uint256 b) internal pure returns (uint256) { uint c = a ** b; assert(c >= a); return c; } } contract Owned { event NewOwner(address old, address current); event NewPotentialOwner(address old, address potential); address public owner = msg.sender; address public potentialOwner; modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyPotentialOwner { require(msg.sender == potentialOwner); _; } function setOwner(address _new) public onlyOwner { emit NewPotentialOwner(owner, _new); potentialOwner = _new; } function confirmOwnership() public onlyPotentialOwner { emit NewOwner(owner, potentialOwner); owner = potentialOwner; potentialOwner = 0; } } contract Managed is Owned { event NewManager(address owner, address manager); mapping (address => bool) public manager; modifier onlyManager() { require(manager[msg.sender] == true || msg.sender == owner); _; } function setManager(address _manager) public onlyOwner { emit NewManager(owner, _manager); manager[_manager] = true; } function superManager(address _manager) internal { emit NewManager(owner, _manager); manager[_manager] = true; } function delManager(address _manager) public onlyOwner { emit NewManager(owner, _manager); manager[_manager] = false; } } /// @title Abstract Token, ERC20 token interface contract ERC20 { function name() constant public returns (string); function symbol() constant public returns (string); function decimals() constant public returns (uint8); function totalSupply() constant public returns (uint256); function balanceOf(address owner) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /// Full complete implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 contract StandardToken is SafeMath, ERC20 { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; /// @dev Returns number of tokens owned by given address. function name() public view returns (string) { return name; } /// @dev Returns number of tokens owned by given address. function symbol() public view returns (string) { return symbol; } /// @dev Returns number of tokens owned by given address. function decimals() public view returns (uint8) { return decimals; } /// @dev Returns number of tokens owned by given address. function totalSupply() public view returns (uint256) { return totalSupply; } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /// @dev Transfers sender&#39;s tokens to a given address. Returns success. /// @param _to Address of token receiver. /// @param _value Number of tokens to transfer. function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(this)); //prevent direct send to contract if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } else { return false; } } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } } /** @title ERC827 interface, an extension of ERC20 token standard Interface of a ERC827 token, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. */ contract ERC827 { function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); } /** @title ERC827, an extension of ERC20 token standard Implementation the ERC827, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, StandardToken { /** @dev Addition to ERC20 token methods. It allows to approve the transfer of value and execute a call with the sent data. Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 @param _spender The address that will spend the funds. @param _value The amount of tokens to be spent. @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); require(_spender.call(_data)); return true; } function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transfer(_to, _value); require(_to.call(_data)); return true; } function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); require(_to.call(_data)); return true; } } contract MintableToken is ERC827Token { uint256 constant maxSupply = 1e30; // max amount of tokens 1 trillion bool internal mintable = true; modifier isMintable() { require(mintable); _; } function stopMint() internal { mintable = false; } // triggered when the total supply is increased event Issuance(uint256 _amount); // triggered when the total supply is decreased event Destruction(uint256 _amount); /** @dev increases the token supply and sends the new tokens to an account can only be called by the contract owner @param _to account to receive the new amount @param _amount amount to increase the supply by */ function issue(address _to, uint256 _amount) internal { assert(totalSupply + _amount <= maxSupply); // prevent overflows totalSupply += _amount; balances[_to] += _amount; emit Issuance(_amount); emit Transfer(this, _to, _amount); } /** @dev removes tokens from an account and decreases the token supply can only be called by the contract owner (if robbers detected, if will be consensus about token amount) @param _from account to remove the amount from @param _amount amount to decrease the supply by */ /* function destroy(address _from, uint256 _amount) public onlyOwner { balances[_from] -= _amount; _totalSupply -= _amount; Transfer(_from, this, _amount); Destruction(_amount); } */ } contract PaymentManager is MintableToken, Owned { uint256 public receivedWais; uint256 internal _price; bool internal paused = false; modifier isSuspended() { require(!paused); _; } function setPrice(uint256 _value) public onlyOwner returns (bool) { _price = _value; return true; } function watchPrice() public view returns (uint256 price) { return _price; } function rateSystem(address _to, uint256 _value) internal returns (bool) { uint256 _amount; if(_value >= (1 ether / 1000) && _value <= 1 ether) { _amount = _value * _price; } else if(_value >= 1 ether) { _amount = divsm(powsm(_value, 2), 1 ether) * _price; } issue(_to, _amount); if(paused == false) { if(totalSupply > 1 * 10e9 * 1 * 1 ether) paused = true; // if more then 10 billions stop sell } return true; } /** @dev transfer ethereum from contract */ function transferEther(address _to, uint256 _value) public onlyOwner { _to.transfer(_value); } } contract InvestBox is PaymentManager, Managed { // triggered when the amount of reaward are changed event BonusChanged(uint256 _amount); // triggered when making invest event Invested(address _from, uint256 _value); // triggered when invest closed or updated event InvestClosed(address _who, uint256 _value); // triggered when counted event Counted(address _sender, uint256 _intervals); uint256 constant _day = 24 * 60 * 60 * 1 seconds; bytes5 internal _td = bytes5("day"); bytes5 internal _tw = bytes5("week"); bytes5 internal _tm = bytes5("month"); bytes5 internal _ty = bytes5("year"); uint256 internal _creation; uint256 internal _1sty; uint256 internal _2ndy; uint256 internal min_invest; uint256 internal max_invest; struct invest { bool exists; uint256 balance; uint256 created; // creation time uint256 closed; // closing time } mapping (address => mapping (bytes5 => invest)) public investInfo; function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } /** @dev return in interface string encoded to bytes (max len 5 bytes) */ function stringToBytes5(string _data) public pure returns (bytes5) { return bytes5(stringToBytes32(_data)); } struct intervalBytecodes { string day; string week; string month; string year; } intervalBytecodes public IntervalBytecodes; /** @dev setter min max params for investition */ function setMinMaxInvestValue(uint256 _min, uint256 _max) public onlyOwner { min_invest = _min * 10 ** uint256(decimals); max_invest = _max * 10 ** uint256(decimals); } /** @dev number of complete cycles d/m/w/y */ function countPeriod(address _investor, bytes5 _t) internal view returns (uint256) { uint256 _period; uint256 _now = now; // blocking timestamp if (_t == _td) _period = 1 * _day; if (_t == _tw) _period = 7 * _day; if (_t == _tm) _period = 31 * _day; if (_t == _ty) _period = 365 * _day; invest storage inv = investInfo[_investor][_t]; if (_now - inv.created < _period) return 0; return (_now - inv.created)/_period; // get full days } /** @dev loop &#39;for&#39; wrapper, where 100,000%, 10^3 decimal */ function loopFor(uint256 _condition, uint256 _data, uint256 _bonus) internal pure returns (uint256 r) { assembly { for { let i := 0 } lt(i, _condition) { i := add(i, 1) } { let m := mul(_data, _bonus) let d := div(m, 100000) _data := add(_data, d) } r := _data } } /** @dev invest box controller */ function rewardController(address _investor, bytes5 _type) internal view returns (uint256) { uint256 _period; uint256 _balance; uint256 _created; invest storage inv = investInfo[msg.sender][_type]; _period = countPeriod(_investor, _type); _balance = inv.balance; _created = inv.created; uint256 full_steps; uint256 last_step; uint256 _d; if(_type == _td) _d = 365; if(_type == _tw) _d = 54; if(_type == _tm) _d = 12; if(_type == _ty) _d = 1; full_steps = _period/_d; last_step = _period - (full_steps * _d); for(uint256 i=0; i<full_steps; i++) { // not executed if zero _balance = compaundIntrest(_d, _type, _balance, _created); _created += 1 years; } if(last_step > 0) _balance = compaundIntrest(last_step, _type, _balance, _created); return _balance; } /** @dev Compaund Intrest realization, return balance + Intrest @param _period - time interval dependent from invest time */ function compaundIntrest(uint256 _period, bytes5 _type, uint256 _balance, uint256 _created) internal view returns (uint256) { uint256 full_steps; uint256 last_step; uint256 _d = 100; // safe divider uint256 _bonus = bonusSystem(_type, _created); if (_period>_d) { full_steps = _period/_d; last_step = _period - (full_steps * _d); for(uint256 i=0; i<full_steps; i++) { _balance = loopFor(_d, _balance, _bonus); } if(last_step > 0) _balance = loopFor(last_step, _balance, _bonus); } else if (_period<=_d) { _balance = loopFor(_period, _balance, _bonus); } return _balance; } /** @dev Bonus program */ function bonusSystem(bytes5 _t, uint256 _now) internal view returns (uint256) { uint256 _b; if (_t == _td) { if (_now < _1sty) { _b = 600; // 0.6 %/day // 100.6 % by day => 887.69 % by year } else if (_now >= _1sty && _now < _2ndy) { _b = 300; // 0.3 %/day } else if (_now >= _2ndy) { _b = 30; // 0.03 %/day } } if (_t == _tw) { if (_now < _1sty) { _b = 5370; // 0.75 %/day => 5.37 % by week => 1529.13 % by year } else if (_now >= _1sty && _now < _2ndy) { _b = 2650; // 0.375 %/day } else if (_now >= _2ndy) { _b = 270; // 0.038 %/day } } if (_t == _tm) { if (_now < _1sty) { _b = 30000; // 0.85 %/day // 130 % by month => 2196.36 % by year } else if (_now >= _1sty && _now < _2ndy) { _b = 14050; // 0.425 %/day } else if (_now >= _2ndy) { _b = 1340; // 0.043 %/day } } if (_t == _ty) { if (_now < _1sty) { _b = 3678000; // 1 %/day // 3678.34 * 1000 = 3678340 = 3678% by year } else if (_now >= _1sty && _now < _2ndy) { _b = 517470; // 0.5 %/day } else if (_now >= _2ndy) { _b = 20020; // 0.05 %/day } } return _b; } /** @dev make invest */ function makeInvest(uint256 _value, bytes5 _interval) internal isMintable { require(min_invest <= _value && _value <= max_invest); // min max condition assert(balances[msg.sender] >= _value && balances[this] + _value > balances[this]); balances[msg.sender] -= _value; balances[this] += _value; invest storage inv = investInfo[msg.sender][_interval]; if (inv.exists == false) { // if invest no exists inv.balance = _value; inv.created = now; inv.closed = 0; emit Transfer(msg.sender, this, _value); } else if (inv.exists == true) { uint256 rew = rewardController(msg.sender, _interval); inv.balance = _value + rew; inv.closed = 0; emit Transfer(0x0, this, rew); // fix rise total supply } inv.exists = true; emit Invested(msg.sender, _value); if(totalSupply > maxSupply) stopMint(); // stop invest } function makeDailyInvest(uint256 _value) public { makeInvest(_value * 10 ** uint256(decimals), _td); } function makeWeeklyInvest(uint256 _value) public { makeInvest(_value * 10 ** uint256(decimals), _tw); } function makeMonthlyInvest(uint256 _value) public { makeInvest(_value * 10 ** uint256(decimals), _tm); } function makeAnnualInvest(uint256 _value) public { makeInvest(_value * 10 ** uint256(decimals), _ty); } /** @dev close invest */ function closeInvest(bytes5 _interval) internal { uint256 _intrest; address _to = msg.sender; uint256 _period = countPeriod(_to, _interval); invest storage inv = investInfo[_to][_interval]; uint256 _value = inv.balance; if (_period == 0) { balances[this] -= _value; balances[_to] += _value; emit Transfer(this, _to, _value); // tx of begining balance emit InvestClosed(_to, _value); } else if (_period > 0) { // Destruction init balances[this] -= _value; totalSupply -= _value; emit Transfer(this, 0x0, _value); emit Destruction(_value); // Issue init _intrest = rewardController(_to, _interval); if(manager[msg.sender]) { _intrest = mulsm(divsm(_intrest, 100), 105); // addition 5% bonus for manager } issue(_to, _intrest); // tx of % emit InvestClosed(_to, _intrest); } inv.exists = false; // invest inv clear inv.balance = 0; inv.closed = now; } function closeDailyInvest() public { closeInvest(_td); } function closeWeeklyInvest() public { closeInvest(_tw); } function closeMonthlyInvest() public { closeInvest(_tm); } function closeAnnualInvest() public { closeInvest(_ty); } /** @dev safe closing invest, checking for complete by date. */ function isFullInvest(address _ms, bytes5 _t) internal returns (uint256) { uint256 res = countPeriod(_ms, _t); emit Counted(msg.sender, res); return res; } function countDays() public returns (uint256) { return isFullInvest(msg.sender, _td); } function countWeeks() public returns (uint256) { return isFullInvest(msg.sender, _tw); } function countMonths() public returns (uint256) { return isFullInvest(msg.sender, _tm); } function countYears() public returns (uint256) { return isFullInvest(msg.sender, _ty); } } contract EthereumRisen is InvestBox { // devs addresess, pay for code address public devWallet = address(0x00FBB38c017843DFa86a97c31fECaCFF0a092F6F); uint256 constant public devReward = 100000 * 1e18; // 100K // fondation for pay by promotion this project address public bountyWallet = address(0x00Ed07D0170B1c5F3EeDe1fC7261719e04b15ecD); uint256 constant public bountyReward = 50000 * 1e18; // 50K // will be send for first 10k rischest wallets, if it is enough to pay the commission address public airdropWallet = address(0x000DdB5A903d15b2F7f7300f672d2EB9bF882143); uint256 constant public airdropReward = 99900 * 1e18; // 99.9K bool internal _airdrop_status = false; uint256 internal _paySize; /** init airdrop program if cap will reach сost price */ function startAirdrop() public onlyOwner { if(address(this).balance < 5 ether && _airdrop_status == true) revert(); issue(airdropWallet, airdropReward); _paySize = 999 * 1e16; // 9.99 tokens _airdrop_status = true; } /** @dev notify owners about their balances was in promo action. @param _holders addresses of the owners to be notified ["address_1", "address_2", ..] */ function airdropper(address [] _holders, uint256 _pay_size) public onlyManager { if(_pay_size == 0) _pay_size = _paySize; // if empty set default if(_pay_size < 1 * 1e18) revert(); // limit no less then 1 token uint256 count = _holders.length; require(count <= 200); assert(_pay_size * count <= balanceOf(msg.sender)); for (uint256 i = 0; i < count; i++) { transfer(_holders [i], _pay_size); } } function EthereumRisen() public { name = "Ethereum Risen"; symbol = "ETR"; decimals = 18; totalSupply = 0; _creation = now; _1sty = now + 365 * 1 days; _2ndy = now + 2 * 365 * 1 days; PaymentManager.setPrice(10000); Managed.setManager(bountyWallet); InvestBox.IntervalBytecodes = intervalBytecodes( "0x6461790000", "0x7765656b00", "0x6d6f6e7468", "0x7965617200" ); InvestBox.setMinMaxInvestValue(1000,100000000); issue(bountyWallet, bountyReward); issue(devWallet, devReward); } function() public payable isSuspended { require(msg.value >= (1 ether / 100)); if(msg.value >= 5 ether) superManager(msg.sender); // you can make airdrop from this contract rateSystem(msg.sender, msg.value); receivedWais = addsm(receivedWais, msg.value); // count ether which was spent to contract } }
safe closing invest, checking for complete by date. /
function isFullInvest(address _ms, bytes5 _t) internal returns (uint256) { uint256 res = countPeriod(_ms, _t); emit Counted(msg.sender, res); return res; }
2,369,435
./full_match/5/0x81c7a9d494c74F113cCa32d174925352bD3875f1/sources/_connext/nxtp-contracts/contracts/core/shared/Router.sol
Assert that the given domain has a xApp Router registered and return its address _domain The domain of the chain for which to get the xApp Router return _remote The address of the remote xApp Router on _domain/
function _mustHaveRemote(uint32 _domain) internal view returns (bytes32 _remote) { _remote = remotes[_domain]; require(_remote != bytes32(0), "!remote"); }
1,910,857
pragma solidity ^0.4.24; import "./ISTO.sol"; import "../../interfaces/IST20.sol"; import "../../interfaces/IOracle.sol"; import "../../RegistryUpdater.sol"; import "../../interfaces/ISecurityTokenRegistry.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ReentrancyGuard.sol"; /** * @title STO module for standard capped crowdsale */ contract USDTieredSTO is ISTO, ReentrancyGuard { using SafeMath for uint256; ///////////// // Storage // ///////////// // Address where ETH & POLY funds are delivered address public wallet; // Address of issuer reserve wallet for unsold tokens address public reserveWallet; // How many token units a buyer gets per USD per tier (multiplied by 10**18) uint256[] public ratePerTier; // How many token units a buyer gets per USD per tier (multiplied by 10**18) when investing in POLY up to tokensPerTierDiscountPoly uint256[] public ratePerTierDiscountPoly; // How many tokens are available in each tier (relative to totalSupply) uint256[] public tokensPerTierTotal; // How many token units are available in each tier (relative to totalSupply) at the ratePerTierDiscountPoly rate uint256[] public tokensPerTierDiscountPoly; // How many tokens have been minted in each tier (relative to totalSupply) uint256[] public mintedPerTierTotal; // How many tokens have been minted in each tier (relative to totalSupply) at ETH rate uint256[] public mintedPerTierETH; // How many tokens have been minted in each tier (relative to totalSupply) at regular POLY rate uint256[] public mintedPerTierRegularPoly; // How many tokens have been minted in each tier (relative to totalSupply) at discounted POLY rate uint256[] public mintedPerTierDiscountPoly; // Current tier uint8 public currentTier; // Amount of USD funds raised uint256 public fundsRaisedUSD; // Amount of ETH funds raised uint256 public fundsRaisedETH; // Amount of POLY funds raised uint256 public fundsRaisedPOLY; // Number of individual investors uint256 public investorCount; // Amount in USD invested by each address mapping (address => uint256) public investorInvestedUSD; // Amount in ETH invested by each address mapping (address => uint256) public investorInvestedETH; // Amount in POLY invested by each address mapping (address => uint256) public investorInvestedPOLY; // List of accredited investors mapping (address => bool) public accredited; // Limit in USD for non-accredited investors multiplied by 10**18 uint256 public nonAccreditedLimitUSD; // Minimum investable amount in USD uint256 public minimumInvestmentUSD; // Whether or not the STO has been finalized bool public isFinalized; // Final amount of tokens sold uint256 public finalAmountSold; // Final amount of tokens returned to issuer uint256 public finalAmountReturned; //////////// // Events // //////////// event TokenPurchase(address indexed _purchaser, address indexed _beneficiary, uint256 _tokens, uint256 _usdAmount, uint256 _tierPrice, uint8 _tier); event FundsReceivedETH(address indexed _purchaser, address indexed _beneficiary, uint256 _usdAmount, uint256 _receivedValue, uint256 _spentValue, uint256 _rate); event FundsReceivedPOLY(address indexed _purchaser, address indexed _beneficiary, uint256 _usdAmount, uint256 _receivedValue, uint256 _spentValue, uint256 _rate); event ReserveTokenMint(address indexed _owner, address indexed _wallet, uint256 _tokens, uint8 _tier); event SetAddresses( address indexed _wallet, address indexed _reserveWallet ); event SetLimits( uint256 _nonAccreditedLimitUSD, uint256 _minimumInvestmentUSD ); event SetFunding( uint8[] _fundRaiseTypes ); event SetTimes( uint256 _startTime, uint256 _endTime ); event SetTiers( uint256[] _ratePerTier, uint256[] _ratePerTierDiscountPoly, uint256[] _tokensPerTierTotal, uint256[] _tokensPerTierDiscountPoly ); /////////////// // Modifiers // /////////////// modifier validETH { require(ISecurityTokenRegistry(RegistryUpdater(securityToken).securityTokenRegistry()).getOracle(bytes32("ETH"), bytes32("USD")) != address(0), "Invalid ETHUSD Oracle"); require(fundRaiseType[uint8(FundRaiseType.ETH)]); _; } modifier validPOLY { require(ISecurityTokenRegistry(RegistryUpdater(securityToken).securityTokenRegistry()).getOracle(bytes32("POLY"), bytes32("USD")) != address(0), "Invalid ETHUSD Oracle"); require(fundRaiseType[uint8(FundRaiseType.POLY)]); _; } /////////////////////// // STO Configuration // /////////////////////// constructor (address _securityToken, address _polyAddress) public IModule(_securityToken, _polyAddress) { } /** * @notice Function used to intialize the contract variables * @param _startTime Unix timestamp at which offering get started * @param _endTime Unix timestamp at which offering get ended * @param _ratePerTier Rate (in USD) per tier (* 10**18) * @param _tokensPerTierTotal Tokens available in each tier * @param _nonAccreditedLimitUSD Limit in USD (* 10**18) for non-accredited investors * @param _minimumInvestmentUSD Minimun investment in USD (* 10**18) * @param _fundRaiseTypes Types of currency used to collect the funds * @param _wallet Ethereum account address to hold the funds * @param _reserveWallet Ethereum account address to receive unsold tokens */ function configure( uint256 _startTime, uint256 _endTime, uint256[] _ratePerTier, uint256[] _ratePerTierDiscountPoly, uint256[] _tokensPerTierTotal, uint256[] _tokensPerTierDiscountPoly, uint256 _nonAccreditedLimitUSD, uint256 _minimumInvestmentUSD, uint8[] _fundRaiseTypes, address _wallet, address _reserveWallet ) public onlyFactory { _configureFunding(_fundRaiseTypes); _configureAddresses(_wallet, _reserveWallet); _configureTiers(_ratePerTier, _ratePerTierDiscountPoly, _tokensPerTierTotal, _tokensPerTierDiscountPoly); _configureTimes(_startTime, _endTime); _configureLimits(_nonAccreditedLimitUSD, _minimumInvestmentUSD); } function modifyFunding(uint8[] _fundRaiseTypes) public onlyOwner { require(now < startTime); _configureFunding(_fundRaiseTypes); } function modifyLimits( uint256 _nonAccreditedLimitUSD, uint256 _minimumInvestmentUSD ) public onlyOwner { require(now < startTime); _configureLimits(_nonAccreditedLimitUSD, _minimumInvestmentUSD); } function modifyTiers( uint256[] _ratePerTier, uint256[] _ratePerTierDiscountPoly, uint256[] _tokensPerTierTotal, uint256[] _tokensPerTierDiscountPoly ) public onlyOwner { require(now < startTime); _configureTiers(_ratePerTier, _ratePerTierDiscountPoly, _tokensPerTierTotal, _tokensPerTierDiscountPoly); } function modifyTimes( uint256 _startTime, uint256 _endTime ) public onlyOwner { require(now < startTime); _configureTimes(_startTime, _endTime); } function modifyAddresses( address _wallet, address _reserveWallet ) public onlyOwner { require(now < startTime); _configureAddresses(_wallet, _reserveWallet); } function _configureFunding(uint8[] _fundRaiseTypes) internal { require(_fundRaiseTypes.length > 0 && _fundRaiseTypes.length < 3, "No fund raising currencies specified"); fundRaiseType[uint8(FundRaiseType.POLY)] = false; fundRaiseType[uint8(FundRaiseType.ETH)] = false; for (uint8 j = 0; j < _fundRaiseTypes.length; j++) { require(_fundRaiseTypes[j] < 2); fundRaiseType[_fundRaiseTypes[j]] = true; } emit SetFunding(_fundRaiseTypes); } function _configureLimits( uint256 _nonAccreditedLimitUSD, uint256 _minimumInvestmentUSD ) internal { minimumInvestmentUSD = _minimumInvestmentUSD; nonAccreditedLimitUSD = _nonAccreditedLimitUSD; emit SetLimits(minimumInvestmentUSD, nonAccreditedLimitUSD); } function _configureTiers( uint256[] _ratePerTier, uint256[] _ratePerTierDiscountPoly, uint256[] _tokensPerTierTotal, uint256[] _tokensPerTierDiscountPoly ) internal { require(_tokensPerTierTotal.length > 0); require(_ratePerTier.length == _tokensPerTierTotal.length, "Mismatch between rates and tokens per tier"); require(_ratePerTierDiscountPoly.length == _tokensPerTierTotal.length, "Mismatch between discount rates and tokens per tier"); require(_tokensPerTierDiscountPoly.length == _tokensPerTierTotal.length, "Mismatch between discount tokens per tier and tokens per tier"); for (uint8 i = 0; i < _ratePerTier.length; i++) { require(_ratePerTier[i] > 0, "Rate of token should be greater than 0"); require(_tokensPerTierTotal[i] > 0, "Tokens per tier should be greater than 0"); require(_tokensPerTierDiscountPoly[i] <= _tokensPerTierTotal[i], "Discounted tokens per tier should be less than or equal to tokens per tier"); require(_ratePerTierDiscountPoly[i] <= _ratePerTier[i], "Discounted rate per tier should be less than or equal to rate per tier"); } mintedPerTierTotal = new uint256[](_ratePerTier.length); mintedPerTierETH = new uint256[](_ratePerTier.length); mintedPerTierRegularPoly = new uint256[](_ratePerTier.length); mintedPerTierDiscountPoly = new uint256[](_ratePerTier.length); ratePerTier = _ratePerTier; ratePerTierDiscountPoly = _ratePerTierDiscountPoly; tokensPerTierTotal = _tokensPerTierTotal; tokensPerTierDiscountPoly = _tokensPerTierDiscountPoly; emit SetTiers(_ratePerTier, _ratePerTierDiscountPoly, _tokensPerTierTotal, _tokensPerTierDiscountPoly); } function _configureTimes( uint256 _startTime, uint256 _endTime ) internal { require(_endTime > _startTime, "Date parameters are not valid"); require(_startTime > now, "Start Time must be in the future"); startTime = _startTime; endTime = _endTime; emit SetTimes(_startTime, _endTime); } function _configureAddresses( address _wallet, address _reserveWallet ) internal { require(_wallet != address(0), "Zero address is not permitted for wallet"); require(_reserveWallet != address(0), "Zero address is not permitted for wallet"); wallet = _wallet; reserveWallet = _reserveWallet; emit SetAddresses(_wallet, _reserveWallet); } //////////////////// // STO Management // //////////////////// /** * @notice Finalize the STO and mint remaining tokens to reserve address * @notice Reserve address must be whitelisted to successfully finalize */ function finalize() public onlyOwner { require(!isFinalized); isFinalized = true; uint256 tempReturned; uint256 tempSold; uint256 remainingTokens; for (uint8 i = 0; i < tokensPerTierTotal.length; i++) { remainingTokens = tokensPerTierTotal[i].sub(mintedPerTierTotal[i]); tempReturned = tempReturned.add(remainingTokens); tempSold = tempSold.add(mintedPerTierTotal[i]); if (remainingTokens > 0) { mintedPerTierTotal[i] = tokensPerTierTotal[i]; require(IST20(securityToken).mint(reserveWallet, remainingTokens), "Error in minting the tokens"); emit ReserveTokenMint(msg.sender, reserveWallet, remainingTokens, i); } } finalAmountReturned = tempReturned; finalAmountSold = tempSold; } /** * @notice Modify the list of accredited addresses * @param _investors Array of investor addresses to modify * @param _accredited Array of bools specifying accreditation status */ function changeAccredited(address[] _investors, bool[] _accredited) public onlyOwner { require(_investors.length == _accredited.length); for (uint256 i = 0; i < _investors.length; i++) { accredited[_investors[i]] = _accredited[i]; } } ////////////////////////// // Investment Functions // ////////////////////////// /** * @notice fallback function - assumes ETH being invested */ function () external payable { buyWithETH(msg.sender); } /** * @notice Purchase tokens using ETH * @param _beneficiary Address where security tokens will be sent */ function buyWithETH(address _beneficiary) public payable validETH { uint256 rate = IOracle(ISecurityTokenRegistry(RegistryUpdater(securityToken).securityTokenRegistry()).getOracle(bytes32("ETH"), bytes32("USD"))).getPrice(); (uint256 spentUSD, uint256 spentValue) = _buyTokens(_beneficiary, msg.value, rate, false); // Modify storage investorInvestedETH[_beneficiary] = investorInvestedETH[_beneficiary].add(spentValue); fundsRaisedETH = fundsRaisedETH.add(spentValue); // Forward ETH to issuer wallet wallet.transfer(spentValue); // Refund excess ETH to investor wallet msg.sender.transfer(msg.value.sub(spentValue)); emit FundsReceivedETH(msg.sender, _beneficiary, spentUSD, msg.value, spentValue, rate); } /** * @notice Purchase tokens using POLY * @param _beneficiary Address where security tokens will be sent * @param _investedPOLY Amount of POLY invested */ function buyWithPOLY(address _beneficiary, uint256 _investedPOLY) public validPOLY { uint256 rate = IOracle(ISecurityTokenRegistry(RegistryUpdater(securityToken).securityTokenRegistry()).getOracle(bytes32("POLY"), bytes32("USD"))).getPrice(); (uint256 spentUSD, uint256 spentValue) = _buyTokens(_beneficiary, _investedPOLY, rate, true); // Modify storage investorInvestedPOLY[_beneficiary] = investorInvestedPOLY[_beneficiary].add(spentValue); fundsRaisedPOLY = fundsRaisedPOLY.add(spentValue); // Forward POLY to issuer wallet require(polyToken.transferFrom(msg.sender, wallet, spentValue)); emit FundsReceivedPOLY(msg.sender, _beneficiary, spentUSD, _investedPOLY, spentValue, rate); } /** * @notice Low level token purchase * @param _beneficiary Address where security tokens will be sent * @param _investmentValue Amount of POLY or ETH invested * @param _isPOLY Investment method */ function _buyTokens(address _beneficiary, uint256 _investmentValue, uint256 _rate, bool _isPOLY) internal nonReentrant whenNotPaused returns(uint256, uint256) { require(isOpen(), "STO is not open"); require(_investmentValue > 0, "No funds were sent to buy tokens"); uint256 investedUSD = decimalMul(_rate, _investmentValue); // Check for minimum investment require(investedUSD.add(investorInvestedUSD[_beneficiary]) >= minimumInvestmentUSD, "Total investment less than minimumInvestmentUSD"); // Check for non-accredited cap if (!accredited[_beneficiary]) { require(investorInvestedUSD[_beneficiary] < nonAccreditedLimitUSD, "Non-accredited investor has already reached nonAccreditedLimitUSD"); if (investedUSD.add(investorInvestedUSD[_beneficiary]) > nonAccreditedLimitUSD) investedUSD = nonAccreditedLimitUSD.sub(investorInvestedUSD[_beneficiary]); } uint256 spentUSD; // Iterate over each tier and process payment for (uint8 i = currentTier; i < ratePerTier.length; i++) { // Update current tier if needed if (currentTier != i) currentTier = i; // If there are tokens remaining, process investment if (mintedPerTierTotal[i] < tokensPerTierTotal[i]) spentUSD = spentUSD.add(_calculateTier(_beneficiary, i, investedUSD.sub(spentUSD), _isPOLY)); // If all funds have been spent, exit the loop if (investedUSD == spentUSD) break; } // Modify storage if (spentUSD > 0) { if (investorInvestedUSD[_beneficiary] == 0) investorCount = investorCount + 1; investorInvestedUSD[_beneficiary] = investorInvestedUSD[_beneficiary].add(spentUSD); fundsRaisedUSD = fundsRaisedUSD.add(spentUSD); } // Calculate spent in base currency (ETH or POLY) uint256 spentValue = decimalDiv(spentUSD, _rate); // Return calculated amounts return (spentUSD, spentValue); } function _calculateTier(address _beneficiary, uint8 _tier, uint256 _investedUSD, bool _isPOLY) internal returns(uint256) { // First purchase any discounted tokens if POLY investment uint256 spentUSD; uint256 tierSpentUSD; uint256 tierPurchasedTokens; // Check whether there are any remaining discounted tokens if (_isPOLY && tokensPerTierDiscountPoly[_tier] > mintedPerTierDiscountPoly[_tier]) { uint256 discountRemaining = tokensPerTierDiscountPoly[_tier].sub(mintedPerTierDiscountPoly[_tier]); uint256 totalRemaining = tokensPerTierTotal[_tier].sub(mintedPerTierTotal[_tier]); if (totalRemaining < discountRemaining) (spentUSD, tierPurchasedTokens) = _purchaseTier(_beneficiary, ratePerTierDiscountPoly[_tier], totalRemaining, _investedUSD, _tier); else (spentUSD, tierPurchasedTokens) = _purchaseTier(_beneficiary, ratePerTierDiscountPoly[_tier], discountRemaining, _investedUSD, _tier); _investedUSD = _investedUSD.sub(spentUSD); mintedPerTierDiscountPoly[_tier] = mintedPerTierDiscountPoly[_tier].add(tierPurchasedTokens); mintedPerTierTotal[_tier] = mintedPerTierTotal[_tier].add(tierPurchasedTokens); } // Now, if there is any remaining USD to be invested, purchase at non-discounted rate if (_investedUSD > 0) { (tierSpentUSD, tierPurchasedTokens) = _purchaseTier(_beneficiary, ratePerTier[_tier], tokensPerTierTotal[_tier].sub(mintedPerTierTotal[_tier]), _investedUSD, _tier); spentUSD = spentUSD.add(tierSpentUSD); if (_isPOLY) mintedPerTierRegularPoly[_tier] = mintedPerTierRegularPoly[_tier].add(tierPurchasedTokens); else mintedPerTierETH[_tier] = mintedPerTierETH[_tier].add(tierPurchasedTokens); mintedPerTierTotal[_tier] = mintedPerTierTotal[_tier].add(tierPurchasedTokens); } return spentUSD; } function _purchaseTier(address _beneficiary, uint256 _tierPrice, uint256 _tierRemaining, uint256 _investedUSD, uint8 _tier) internal returns(uint256, uint256) { uint256 maximumTokens = decimalDiv(_investedUSD, _tierPrice); uint256 spentUSD; uint256 purchasedTokens; if (maximumTokens > _tierRemaining) { spentUSD = decimalMul(_tierRemaining, _tierPrice); purchasedTokens = _tierRemaining; } else { spentUSD = _investedUSD; purchasedTokens = maximumTokens; } require(IST20(securityToken).mint(_beneficiary, purchasedTokens), "Error in minting the tokens"); emit TokenPurchase(msg.sender, _beneficiary, purchasedTokens, spentUSD, _tierPrice, _tier); return (spentUSD, purchasedTokens); } ///////////// // Getters // ///////////// /** * @notice This function returns whether or not the STO is in fundraising mode (open) * @return bool Whether the STO is accepting investments */ function isOpen() public view returns(bool) { if (isFinalized) return false; if (now < startTime) return false; if (now >= endTime) return false; if (capReached()) return false; return true; } /** * @notice This function converts from ETH or POLY to USD * @param _currency Currency key * @param _amount Value to convert to USD * @return uint256 Value in USD */ function convertToUSD(bytes32 _currency, uint256 _amount) public view returns(uint256) { uint256 rate = IOracle(ISecurityTokenRegistry(RegistryUpdater(securityToken).securityTokenRegistry()).getOracle(_currency, bytes32("USD"))).getPrice(); return decimalMul(_amount, rate); } /** * @notice This function converts from USD to ETH or POLY * @param _currency Currency key * @param _amount Value to convert from USD * @return uint256 Value in ETH or POLY */ function convertFromUSD(bytes32 _currency, uint256 _amount) public view returns(uint256) { uint256 rate = IOracle(ISecurityTokenRegistry(RegistryUpdater(securityToken).securityTokenRegistry()).getOracle(_currency, bytes32("USD"))).getPrice(); return decimalDiv(_amount, rate); } /** * @notice Checks whether the cap has been reached. * @return bool Whether the cap was reached */ function capReached() public view returns (bool) { if (isFinalized) { return (finalAmountReturned == 0); } return (mintedPerTierTotal[mintedPerTierTotal.length - 1] == tokensPerTierTotal[tokensPerTierTotal.length - 1]); } /** * @notice Return ETH raised by the STO * @return uint256 Amount of ETH raised */ function getRaisedEther() public view returns (uint256) { return fundsRaisedETH; } /** * @notice Return POLY raised by the STO * @return uint256 Amount of POLY raised */ function getRaisedPOLY() public view returns (uint256) { return fundsRaisedPOLY; } /** * @notice Return USD raised by the STO * @return uint256 Amount of USD raised */ function getRaisedUSD() public view returns (uint256) { return fundsRaisedUSD; } /** * @notice Return the total no. of investors * @return uint256 Investor count */ function getNumberInvestors() public view returns (uint256) { return investorCount; } /** * @notice Return the total no. of tokens sold * @return uint256 Total number of tokens sold */ function getTokensSold() public view returns (uint256) { if (isFinalized) return finalAmountSold; else return getTokensMinted(); } /** * @notice Return the total no. of tokens minted * @return uint256 Total number of tokens minted */ function getTokensMinted() public view returns (uint256) { uint256 tokensMinted; for (uint8 i = 0; i < mintedPerTierTotal.length; i++) { tokensMinted = tokensMinted.add(mintedPerTierTotal[i]); } return tokensMinted; } /** * @notice Return the total no. of tokens sold for ETH * @return uint256 Total number of tokens sold for ETH */ function getTokensSoldForETH() public view returns (uint256) { uint256 tokensSold; for (uint8 i = 0; i < mintedPerTierETH.length; i++) { tokensSold = tokensSold.add(mintedPerTierETH[i]); } return tokensSold; } /** * @notice Return the total no. of tokens sold for POLY * @return uint256 Total number of tokens sold for POLY */ function getTokensSoldForPOLY() public view returns (uint256) { uint256 tokensSold; for (uint8 i = 0; i < mintedPerTierRegularPoly.length; i++) { tokensSold = tokensSold.add(mintedPerTierRegularPoly[i]).add(mintedPerTierDiscountPoly[i]); } return tokensSold; } /** * @notice Return the total no. of tiers * @return uint256 Total number of tiers */ function getNumberOfTiers() public view returns (uint256) { return tokensPerTierTotal.length; } /** * @notice Return the permissions flag that are associated with STO */ function getPermissions() public view returns(bytes32[]) { bytes32[] memory allPermissions = new bytes32[](0); return allPermissions; } /** * @notice This function returns the signature of configure function * @return bytes4 Configure function signature */ function getInitFunction() public pure returns (bytes4) { return bytes4(keccak256("configure(uint256,uint256,uint256[],uint256[],uint256[],uint256[],uint256,uint256,uint8[],address,address)")); } uint constant DECIMALS = 10 ** 18; /** * @notice This function multiplies two decimals represented as (decimal * 10**DECIMALS) * @return uint256 Result of multiplication represented as (decimal * 10**DECIMALS) */ function decimalMul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = SafeMath.add(SafeMath.mul(x, y), DECIMALS / 2) / DECIMALS; } /** * @notice This function divides two decimals represented as (decimal * 10**DECIMALS) * @return uint256 Result of division represented as (decimal * 10**DECIMALS) */ function decimalDiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = SafeMath.add(SafeMath.mul(x, DECIMALS), y / 2) / y; } }
This function converts from ETH or POLY to USD _currency Currency key _amount Value to convert to USD return uint256 Value in USD/
function convertToUSD(bytes32 _currency, uint256 _amount) public view returns(uint256) { uint256 rate = IOracle(ISecurityTokenRegistry(RegistryUpdater(securityToken).securityTokenRegistry()).getOracle(_currency, bytes32("USD"))).getPrice(); return decimalMul(_amount, rate); }
2,548,323
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract SessionHandler { // Holds the main data about each session struct Session { address player; uint256 timestamp; uint256 id; bool active; } struct Crossword { uint256 hintPrice; uint256 wordPrice; uint256 creationTimestamp; uint256 id; } Session[] public sessions; Crossword[] public crosswords; // Couples a player's address to his last session mapping(address => uint256) public playerLastSessionId; // Owner of the contract, can change prices and withdraw funds address public owner; event NewSessionStarted(address from, uint256 sessionId); event SessionEnded(address from, uint256 sessionId); event RequestHint(address from, uint256 sessionId); event RequestWordReveal(address from, uint256 sessionId); modifier onlyOwner() { require(msg.sender == owner, "You're not the owner of the contract"); _; } modifier onlyPlayer(uint256 _sessionId) { require( msg.sender == sessions[_sessionId].player, "You are not the player of this session!" ); _; } // Sets the prices and the owner constructor() { owner = msg.sender; } /* * Starts a new session and registers the timestamp at which the game started * to later calculate how much time it takes the player to finish the game */ function startSession() public { Session memory session = Session( msg.sender, block.timestamp, sessions.length, true ); sessions.push(session); playerLastSessionId[msg.sender] = session.id; emit NewSessionStarted(msg.sender, session.id); } /* * Ends the game session provided and calculates the total time taken to finish * @dev only the owner can call this function */ function endSession(uint256 _sessionId) public onlyOwner returns (uint256 timeTaken) { Session memory session = sessions[_sessionId]; // gas saver require(session.active, "The session has already ended!"); sessions[_sessionId].active = false; timeTaken = block.timestamp - session.timestamp; emit SessionEnded(msg.sender, _sessionId); } // Request an hint function requestHint(uint256 _sessionId) public onlyPlayer(_sessionId) { // TODO: make token payment emit RequestHint(msg.sender, _sessionId); } // Request a word reveal function requestWord(uint256 _sessionId) public onlyPlayer(_sessionId) { // TODO: make token payment emit RequestWordReveal(msg.sender, _sessionId); } // Some helper methods function getLastSession() public view returns ( address player, uint256 timestamp, uint256 id, bool active ) { return getSessionById(sessions.length - 1); } function getSessionById(uint256 _id) public view returns ( address player, uint256 timestamp, uint256 id, bool active ) { Session memory session = sessions[_id]; player = session.player; timestamp = session.timestamp; id = session.id; active = session.active; } function getPlayerLastSessionId(address _player) public view returns (uint256) { return playerLastSessionId[_player]; } // Withdraw the funds to specified address function withdraw(address payable _to) public onlyOwner { (bool sent, ) = _to.call{value: address(this).balance}(""); require(sent, "Transaction failed!"); } }
Request an hint TODO: make token payment
function requestHint(uint256 _sessionId) public onlyPlayer(_sessionId) { emit RequestHint(msg.sender, _sessionId); }
15,832,358
/** *Submitted for verification at Etherscan.io on 2020-11-24 */ // SPDX-License-Identifier: MIT 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); } } } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT 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"); } } } 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); } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract DexProtect { using SafeERC20 for IERC20; using SafeMath for uint256; // Constants and Default Tokens address uniswapV2Factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address uniswapV2Router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //CHANGE TO MAINET WETH: 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 uint256 maxApproval = 115792089237316195423570985008687907853269984665640564039457584007913129639935; // Script Variables address payable public owner; IERC20 Token; IUniswapV2Router02 public uniswapRouter; IUniswapV2Factory public uniswapFactory; address[] depositers; address[] depositedTokens; uint256 newDeposit; uint256 newToken; address pairAddress; uint256 tradeBalance; uint256 amountTokenSold; uint256 pretradegasCost; uint256 gasCost; uint256 pretradeETHBalance; uint256 ETHpayout; constructor() public { uniswapRouter = IUniswapV2Router02(uniswapV2Router); uniswapFactory = IUniswapV2Factory(uniswapV2Factory); owner = msg.sender; } struct Balance { address[] tokendeposited; uint256[] amountdeposited; uint256 ethpayout; } mapping (address => Balance) balances; modifier _onlyOwner() {require(msg.sender == owner,'You dont have authorization to sell tokens, withdraw them instead');_;} // Deposit any ERC-20 traded on UniswapV2 into the DexProtect contract and specify amount function depositToken(address tokenaddress, uint256 amount) public { // Dont allow deposits of tokens that arent traded on uniswapv2 currently pairAddress = uniswapFactory.getPair(tokenaddress,WETH); require(pairAddress != address(0), "Pair is not traded with ETH on UniswapV2"); // Dont allow deposits greater than current balance Token = IERC20(tokenaddress); require(Token.balanceOf(msg.sender) >= amount,'Exceeds your current wallet balance'); // Store in struct Balance storage balance = balances[msg.sender]; // If it's a new depositer, add address to the list if (balance.tokendeposited.length == 0) { depositers.push(msg.sender); } // If the token has already been deposited before, we just increase user balance newDeposit = 1 ; for (uint i = 0; i < balance.tokendeposited.length; i++) { if (balance.tokendeposited[i] == tokenaddress) { balance.amountdeposited[i] += amount; newDeposit = 0; } } // If this is the first time depositing this token, add it to the users balance if (newDeposit == 1) { balance.tokendeposited.push(tokenaddress); balance.amountdeposited.push(amount); } // transfer the tokens from the sender to this contract Token.safeTransferFrom(msg.sender, address(this), amount); // approve token for DexProtect contract to trade it if it hasn't been yet newToken = 1 ; for (uint j = 0; j < depositedTokens.length; j++) { if (depositedTokens[j] == tokenaddress) { newToken = 0; } } // If this is the first time this token has been sent we need to approve it and add it to list if (newToken == 1) { depositedTokens.push(tokenaddress); Token.approve(uniswapV2Router,maxApproval); } } // Withdraw ERC-20 Tokens from the contract (not ETH) function withdrawToken(address tokenaddress, uint256 amount) public { Token = IERC20(tokenaddress); // Update struct Balance storage balance = balances[msg.sender]; // Withdraw appropriate token from the contract for (uint i = 0; i < balance.tokendeposited.length; i++) { if (balance.tokendeposited[i] == tokenaddress) { require(balance.amountdeposited[i] >= amount,'Exceeds your deposited amount, check ETH payout if sold'); // If it is a withdrawal of all tokens left in the contract, get rid of it if (Token.balanceOf(address(this)) == balance.amountdeposited[i]) { // Get rid of the token in the balance list updateDepositedTokens(tokenaddress); } balance.amountdeposited[i] -= amount; } } Token.safeTransfer(msg.sender, amount); } // Get the way we will trade it function getTradePath(address tokenaddress) internal view returns (address[] memory) { address[] memory path = new address[](2); path[0] = tokenaddress; path[1] = WETH; return path; } // Trigger sell of certain token (CAN ONLY BE CALLED BY OWNER) function emergencySell(address tokenaddress) public _onlyOwner() payable { Token = IERC20(tokenaddress); require(Token.balanceOf(address(this)) > 0,'Contract doesnt hold this token anymore'); tradeBalance = Token.balanceOf(address(this)); pretradeETHBalance = address(this).balance; pretradegasCost = owner.balance; uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(tradeBalance,0,getTradePath(tokenaddress),address(this),now+100); amountTokenSold = tradeBalance.sub(Token.balanceOf(address(this))); gasCost = pretradegasCost.sub(owner.balance); require(amountTokenSold > 0,'Token was not able to be sold'); pretradeETHBalance += gasCost; // add gas cost to the pretrade eth balance ETHpayout = (((address(this).balance).sub(pretradeETHBalance)).mul(9)).div(10); // 90% is paid out to people who held the token, 10% to rug fund and devs as detailed in WP require(ETHpayout > 0,'Gas cost likely higher than liquidation value, didnt sell'); // if value gained from selling is less than gas dont bother (rare edge case) owner.transfer((((address(this).balance).sub(pretradeETHBalance)).mul(1)).div(10)); updateDepositedTokens(tokenaddress); updateBalancesAfterTrade(tokenaddress,amountTokenSold,1-(amountTokenSold.div(tradeBalance)),ETHpayout); } // Delete token from deposited tokens list function updateDepositedTokens(address tokenaddress) internal { // Get rid of the token in the balance list for (uint d = 0; d < depositedTokens.length; d++) { if (depositedTokens[d] == tokenaddress) { delete depositedTokens[d]; } } } // Update balances if a token was sold and increase reward by appropriate amount of ETH function updateBalancesAfterTrade(address tokenaddress, uint256 sold, uint256 portionleft, uint256 gainz) internal { // Find which owners held the token and adjust balances for (uint b = 0; b < depositers.length; b++) { // iterate through people that have sent tokens Balance storage balance = balances[depositers[b]]; for (uint t = 0; t < balance.tokendeposited.length; t++) { if (balance.tokendeposited[t] == tokenaddress && balance.amountdeposited[t] > 0) { balance.ethpayout += (gainz.mul(balance.amountdeposited[t])).div(sold); // increase eth payout balance by proportionate amount balance.amountdeposited[t] = balance.amountdeposited[t] * (portionleft); // reduce token balance by proportionate amount } } } } // When users want to cash ETH out after tokens were sold function requestETHPayout() public { Balance storage balance = balances[msg.sender]; require(balance.ethpayout > 0, 'You dont have enough ETH to cashout'); msg.sender.transfer(balance.ethpayout); balance.ethpayout = 0; } // Get all token balances and amounts based on the user that called it function getMyBalances() view public returns (address[] memory, uint256[] memory, uint256) { return (balances[msg.sender].tokendeposited,balances[msg.sender].amountdeposited,balances[msg.sender].ethpayout); } // Get all token balances and amounts based on the user function getBalances(address useraddress) view public returns (address[] memory, uint256[] memory, uint256) { return (balances[useraddress].tokendeposited,balances[useraddress].amountdeposited,balances[useraddress].ethpayout); } // Get list of all currently deposited tokens in the contract function getDepositedTokens() view public returns (address[] memory) { return depositedTokens; } // Get list of all addresses who have ever deposited in the contract function getDepositers() view public returns (address[] memory) { return depositers; } // So contract can receive ETH after the uniswap trade receive() payable external {} }
Update balances if a token was sold and increase reward by appropriate amount of ETH Find which owners held the token and adjust balances
function updateBalancesAfterTrade(address tokenaddress, uint256 sold, uint256 portionleft, uint256 gainz) internal { Balance storage balance = balances[depositers[b]]; for (uint t = 0; t < balance.tokendeposited.length; t++) { if (balance.tokendeposited[t] == tokenaddress && balance.amountdeposited[t] > 0) { } } }
6,836,788
/** *Submitted for verification at Etherscan.io on 2022-04-02 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.11; 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address Serial */ 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 * Serials of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly {size := extcodesize(account)} return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success,) = recipient.call{value : amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value : value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev 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); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } } error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error AuxQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Base URI string private _baseURI; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 1; } function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev See {IERC721Enumerable-totalSupply}. * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { if (owner == address(0)) revert AuxQueryForZeroAddress(); return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { if (owner == address(0)) revert AuxQueryForZeroAddress(); _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI_ = baseURI(); return bytes(baseURI_).length != 0 ? string(abi.encodePacked(baseURI_, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function baseURI() internal view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } abstract contract OwnerCheck is Ownable { mapping(address => bool) public keeperMap; uint8 private unlocked = 1; event SetKeeper(address addr, bool auth); modifier onlyKeeper(address addr) { require(isKeeper(addr), "caller is not the keeper"); _; } modifier lock() { require(unlocked == 1, 'Contract: LOCKED'); unlocked = 0; _; unlocked = 1; } function setKeeper(address addr, bool auth) public onlyOwner { keeperMap[addr] = auth; emit SetKeeper(addr, auth); } function isKeeper(address addr) public view returns (bool) { return keeperMap[addr]; } } interface IERC20 { function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); } 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 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"); } } } contract MNSNFT is ERC721A, OwnerCheck { using SafeMath for uint256; using Strings for uint256; using SafeERC20 for IERC20; IERC20 public metaToken; //card id start from 1 //nick name=>card id mapping(bytes32 => uint256) private nickNameCardId; //keep lower nick name=>card id for check if nick name already register mapping(bytes32 => uint256) private nickNameLowerCardId; //card id=>nick name mapping(uint256 => bytes32) private cardIdNickName; //user address=>current nick name used in metalk mapping(address => bytes32) private userBindNickName; //price of one nick name uint256 public nickNamePrice = 5e16; uint256 public nickNameMetaPrice; address payable public ethRecipient = payable(0x50884B6452D807576a4B316DDE1944F0B66069A7); bool public useWhiteList = true; bool public metaUseWhiteList = true; //white list merkle root bytes32 public merkleRoot = 0x4660af648282e8881b4beb703d11d5ef2646a5ccc8b8e46e649f3790f6954e39; bytes32 public metaMerkleRoot; //already minted number less than max amount in white list //0-10 is which type mint,0 value means not mint;1 means already mint //16- save already minted //Cryptopunk=1、Meebits=2、Clonex=3、VeeFriends=4、AZUKI=5 //BAYC=6、MAYC=7、Doodle=8、InvisibleFriends=9、Mfers=10 //0 for others mapping(address => uint256) private _alreadyMinted; mapping(address => uint256) private _metaAlreadyMinted; bool public stopped = true; bool public metaStopped = true; struct social { string twitter; string instagram; string facebook; string discord; } mapping(address => social) socialLink; event BuyNickName(address user, bytes32 nickName, uint256 cardId, uint256 nickNamePrice, uint8 _type); event BuyNickNameByMeta(address user, bytes32 nickName, uint256 cardId, uint256 nickNamePrice, uint8 _type); event ChangeBindMNS(address user, uint256 cardId, bytes32 currentNick, bytes32 nick); //just for get function,not store data struct tokenNickName { uint256 tokenId; string nickName; string uri; } constructor(string memory _name, string memory _symbol, IERC20 meta) ERC721A(_name, _symbol) { _setBaseURI("https://storage.googleapis.com/metalk/mns/metadata/"); metaToken = meta; } function buy(bytes32 _nickName, bytes32[] calldata merkleProof, uint64 maxCount, uint8 _type) public payable lock { require(!stopped, 'stopped'); require(msg.value == nickNamePrice, 'eth need more'); (bytes32 lo,bool valid) = lower(_nickName); require(valid, 'name invalid'); require(nickNameLowerCardId[lo] == 0, 'name exists'); if (useWhiteList) { require((_type > 0) && (_type < 11), 'type wrong'); uint256 temp = _alreadyMinted[msg.sender]; (uint64 total, uint16 setValue) = (uint64(temp >> 16), uint16(temp) & (uint16(0x01) << _type)); require(total < uint64(maxCount), 'Insufficient left'); require(setValue == 0, 'type used'); require(_verify(merkleProof, msg.sender, uint256(maxCount), merkleRoot), 'Invalid proof'); _alreadyMinted[msg.sender] = uint256(uint256(total + 1) << 16) | uint256((uint16(temp) | (uint16(0x01) << _type))); } ethRecipient.transfer(nickNamePrice); uint256 cardId = mint(msg.sender, _nickName, lo); emit BuyNickName(msg.sender, _nickName, cardId, nickNamePrice, _type); } //approve meta first function buyUseMeta(bytes32 _nickName, bytes32[] calldata merkleProof, uint64 maxCount, uint8 _type) public payable lock { require(!metaStopped, 'stopped'); (bytes32 lo,bool valid) = lower(_nickName); require(valid, 'name invalid'); require(nickNameLowerCardId[lo] == 0, 'name exists'); if (metaUseWhiteList) { require((_type > 0) && (_type < 11), 'type wrong'); uint256 temp = _metaAlreadyMinted[msg.sender]; (uint64 total, uint16 setValue) = (uint64(temp >> 16), uint16(temp) & (uint16(0x01) << _type)); require(setValue == 0, 'type used'); require(total < uint256(maxCount), 'Insufficient meta left'); require(_verify(merkleProof, msg.sender, uint256(maxCount), metaMerkleRoot), 'Invalid proof'); _metaAlreadyMinted[msg.sender] = uint256(uint256(total + 1) << 16) | uint256((uint16(temp) | (uint16(0x01) << _type))); } metaToken.safeTransferFrom(msg.sender, ethRecipient, nickNameMetaPrice); uint256 cardId = mint(msg.sender, _nickName, lo); emit BuyNickNameByMeta(msg.sender, _nickName, cardId, nickNameMetaPrice, _type); } function mint(address to, bytes32 _nickName, bytes32 lo) private returns (uint cardId){ //card id start from 1 cardId = totalSupply() + 1; _mint(to, 1, new bytes(0), false); (nickNameCardId[_nickName], nickNameLowerCardId[lo], cardIdNickName[cardId]) = (cardId, cardId, _nickName); } function _verify( bytes32[] calldata merkleProof, address sender, uint256 maxAmount, bytes32 _merkleRoot ) private pure returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(sender, maxAmount.toString())); return processProof(merkleProof, leaf) == _merkleRoot; } function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } function changeBindMNS(uint256 cardId) public lock { address owner = ownerOf(cardId); require(msg.sender == owner, "not owner"); emit ChangeBindMNS(msg.sender, cardId, userBindNickName[msg.sender], cardIdNickName[cardId]); userBindNickName[msg.sender] = cardIdNickName[cardId]; } //for user unbind card and sell function clearBindMNS() public lock { bytes32 oldNickName = userBindNickName[msg.sender]; require(oldNickName != 0, "not bind"); uint256 cardId = nickNameCardId[oldNickName]; address owner = ownerOf(cardId); require(msg.sender == owner, "not owner"); emit ChangeBindMNS(msg.sender, cardId, oldNickName, 0); delete userBindNickName[msg.sender]; } function _beforeTokenTransfers( address from, address, uint256 startTokenId, uint256 quantity) internal override { bytes32 currentNickName = userBindNickName[from]; if (currentNickName != 0) { for (uint i = 0; i < quantity; i++) { if (nickNameCardId[currentNickName] == startTokenId + i) { emit ChangeBindMNS(from, startTokenId + i, currentNickName, 0); delete userBindNickName[from]; break; } } } } function userBindInfo(address[] memory user) external view returns (tokenNickName[] memory ret){ uint256 count = user.length; ret = new tokenNickName[](count); for (uint256 i = 0; i < count; i++) { ret[i].nickName = bytes32ToString(userBindNickName[user[i]]); if (userBindNickName[user[i]] != 0) { ret[i].tokenId = nickNameCardId[userBindNickName[user[i]]]; ret[i].uri = tokenURI(ret[i].tokenId); } } } function tokenOf(uint256[] memory tokenIds) external view returns (tokenNickName[] memory ret){ ret = new tokenNickName[](tokenIds.length); for (uint256 i = 0; i < tokenIds.length; i++) { ret[i].tokenId = tokenIds[i]; ret[i].nickName = bytes32ToString(cardIdNickName[tokenIds[i]]); ret[i].uri = tokenURI(tokenIds[i]); } } function bindTwitterByUser(string memory twitter) public { socialLink[msg.sender].twitter = twitter; } function bindInstagramByUser(string memory instagram) public { socialLink[msg.sender].instagram = instagram; } function bindFacebookByUser(string memory facebook) public { socialLink[msg.sender].facebook = facebook; } function bindDiscordByUser(string memory discord) public { socialLink[msg.sender].discord = discord; } function getSocial(address user) public view returns (social memory){ return socialLink[user]; } function getNickNameCardId(bytes32 nick) public view returns (uint256){ return nickNameCardId[nick]; } function getNickNameExist(bytes32 nick) public view returns (bool){ return nickNameLowerCardId[nick] != 0; } function getCardIdNickName(uint256 cardId) public view returns (string memory){ return bytes32ToString(cardIdNickName[cardId]); } function getUserBindNickName(address user) public view returns (string memory){ return bytes32ToString(userBindNickName[user]); } function getUserAddress(bytes32 nick) public view returns (address ret){ uint256 card = nickNameCardId[nick]; if (card != 0) { ret = ownerOf(card); } } //set base uri function setBaseTokenURI(string memory baseTokenURI) external onlyOwner { _setBaseURI(baseTokenURI); } function getBaseURI() public view returns (string memory){ return baseURI(); } function setNickNamePrice(uint256 _nickNamePrice) public onlyOwner { nickNamePrice = _nickNamePrice; } function setNickNameMetaPrice(uint256 price) public onlyOwner { nickNameMetaPrice = price; } function setEthRecipient(address payable _ethRecipient) public onlyOwner { ethRecipient = _ethRecipient; } function bytes32ToString(bytes32 input) private pure returns (string memory){ if (input == 0) { return ""; } uint8 i = 0; while (i < 32 && input[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && input[i] != 0; i++) { bytesArray[i] = input[i]; } return string(bytesArray); } function lower(bytes32 _nickName) private pure returns (bytes32 ret, bool valid){ if (_nickName == 0) { return (ret, false); } bytes memory bytesArray = new bytes(32); for (uint256 i; i < 32; i++) { bytes1 nick = _nickName[i]; if (nick == 0) { break; } else if (nick >= bytes1("A") && nick <= bytes1("Z")) { bytesArray[i] = bytes1(uint8(nick) + 32); } else if ((nick >= bytes1("0") && nick <= bytes1("9")) || (nick >= bytes1("a") && nick <= bytes1("z"))) { bytesArray[i] = _nickName[i]; } else { return (ret, false); } } ret = bytes32(bytesArray); valid = true; } function setUseWhiteList(bool use) public onlyOwner { useWhiteList = use; } function setUseMetaWhiteList(bool use) public onlyOwner { metaUseWhiteList = use; } function setMerkleProof(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } function setMetaMerkleProof(bytes32 _merkleRoot) public onlyOwner { metaMerkleRoot = _merkleRoot; } //index 0 is total minted function getAlreadyMinted(address addr) public view returns (uint64 total, uint8[11] memory typeCount) { total = uint64(_alreadyMinted[addr] >> 16); for (uint i = 0; i < 11; i++) { typeCount[i] = uint8((uint16(_alreadyMinted[addr]) & 2 ** i) >> i); } } function getMetaAlreadyMinted(address addr) public view returns (uint64 metaTotal, uint8[11] memory metaTypeCount) { metaTotal = uint64(_metaAlreadyMinted[addr] >> 16); for (uint i = 0; i < 11; i++) { metaTypeCount[i] = uint8((uint16(_metaAlreadyMinted[addr]) & 2 ** i) >> i); } } function setStopped(bool flag) public onlyOwner { stopped = flag; } function setUseMetaStopped(bool flag) public onlyOwner { metaStopped = flag; } }
for user unbind card and sell
function clearBindMNS() public lock { bytes32 oldNickName = userBindNickName[msg.sender]; require(oldNickName != 0, "not bind"); uint256 cardId = nickNameCardId[oldNickName]; address owner = ownerOf(cardId); require(msg.sender == owner, "not owner"); emit ChangeBindMNS(msg.sender, cardId, oldNickName, 0); delete userBindNickName[msg.sender]; }
2,299,882
./full_match/3/0xA60d91173c76e8B429a29E9115527b52fD7442A3/sources/contracts/ND.sol
Check that the token exists
function _setContentHash(uint256 tokenId, bytes32 contentHash) internal { require(hasRole(MINTER_ROLE, _msgSender()), "NotreDameERC721: must have minter role to mint"); require(_exists(tokenId), "NotreDameERC721: token does not exist"); _contentHashes[tokenId] = contentHash; }
8,138,907
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/proxy/Proxy.sol pragma solidity >=0.6.0 <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 { // solhint-disable-next-line no-inline-assembly 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 {} } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }( data ); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/proxy/IBeacon.sol pragma solidity >=0.6.0 <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); } // File: @openzeppelin/contracts/proxy/BeaconProxy.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}. * * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't * conflict with the storage layout of the implementation behind the proxy. * * _Available since v3.4._ */ contract BeaconProxy is Proxy { /** * @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 private constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Initializes the proxy with `beacon`. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity * constructor. * * Requirements: * * - `beacon` must be a contract with the interface {IBeacon}. */ constructor(address beacon, bytes memory data) public payable { assert( _BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1) ); _setBeacon(beacon, data); } /** * @dev Returns the current beacon address. */ function _beacon() internal view virtual returns (address beacon) { bytes32 slot = _BEACON_SLOT; // solhint-disable-next-line no-inline-assembly assembly { beacon := sload(slot) } } /** * @dev Returns the current implementation address of the associated beacon. */ function _implementation() internal view virtual override returns (address) { return IBeacon(_beacon()).implementation(); } /** * @dev Changes the proxy to use a new beacon. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. * * Requirements: * * - `beacon` must be a contract. * - The implementation returned by `beacon` must be a contract. */ function _setBeacon(address beacon, bytes memory data) internal virtual { require( Address.isContract(beacon), "BeaconProxy: beacon is not a contract" ); require( Address.isContract(IBeacon(beacon).implementation()), "BeaconProxy: beacon implementation is not a contract" ); bytes32 slot = _BEACON_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, beacon) } if (data.length > 0) { Address.functionDelegateCall( _implementation(), data, "BeaconProxy: function call failed" ); } } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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 ); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 {} } // File: contracts/interfaces/ILiquidVestingToken.sol pragma solidity =0.7.6; interface ILiquidVestingToken { enum AddType { MerkleTree, Airdrop } function initialize( string memory _name, string memory _symbol, uint8 _decimals, address _owner, address _factory, address _redeemToken, uint256 _activationTimestamp, uint256 _redeemTimestamp, AddType _type ) external; function overrideFee(uint256 _newFee) external; function addRecipient(address _recipient, uint256 _amount) external; function addRecipients( address[] memory _recipients, uint256[] memory _amounts ) external; function addMerkleRoot( bytes32 _merkleRoot, uint256 _totalAmount, uint8 _v, bytes32 _r, bytes32 _s ) external; function claimTokensByMerkleProof( bytes32[] memory _proof, uint256 _rootId, address _recipient, uint256 _amount ) external; function claimProjectTokensByFeeCollector() external; function redeem(address _recipient, uint256 _amount) external; } // File: contracts/interfaces/ILiquidVestingTokenFactory.sol pragma solidity =0.7.6; pragma abicoder v2; interface ILiquidVestingTokenFactory { function merkleRootSigner() external view returns (address); function feeCollector() external view returns (address); function fee() external view returns (uint256); function getMinFee() external pure returns (uint256); function getMaxFee() external pure returns (uint256); function setMerkleRootSigner(address _newMerkleRootSigner) external; function setFeeCollector(address _newFeeCollector) external; function setFee(uint256 _fee) external; function implementation() external view returns (address); function createLiquidVestingToken( string[] memory name, string[] memory symbol, address redeemToken, uint256[] memory activationTimestamp, uint256[] memory redeemTimestamp, ILiquidVestingToken.AddType addRecipientsType ) external; } // File: contracts/LiquidVestingTokenFactory.sol pragma solidity =0.7.6; /** * @title LiquidVestingTokenFactory * @dev The LiquidVestingTokenFactory contract can be used to create * vesting contracts for any ERC20 token. */ contract LiquidVestingTokenFactory is Ownable, ILiquidVestingTokenFactory { uint256 public constant MIN_FEE = 0; uint256 public constant MAX_FEE = 5000; address private tokenImplementation; address public override merkleRootSigner; address public override feeCollector; uint256 public override fee; event VestingTokenCreated( address indexed redeemToken, address vestingToken ); mapping(address => address[]) public vestingTokensByOriginalToken; /** * @dev Creates a vesting token factory contract. * @param _tokenImplementation Address of LiquidVestingToken contract implementation. * @param _merkleRootSigner Address of Merkle root signer. * @param _feeCollector Address of fee collector. * @param _fee Fee value. */ constructor( address _tokenImplementation, address _merkleRootSigner, address _feeCollector, uint256 _fee ) { require( Address.isContract(_tokenImplementation), "Implementation is not a contract" ); require( _merkleRootSigner != address(0), "Merkle root signer cannot be zero address" ); require( _feeCollector != address(0), "Fee collector cannot be zero address" ); require(_fee >= MIN_FEE && _fee <= MAX_FEE, "Fee goes beyond rank"); merkleRootSigner = _merkleRootSigner; feeCollector = _feeCollector; fee = _fee; tokenImplementation = _tokenImplementation; } /** * @dev Set address of Merkle root signer. * @param _newMerkleRootSigner Address of signer. */ function setMerkleRootSigner(address _newMerkleRootSigner) external override onlyOwner { require( _newMerkleRootSigner != address(0), "Merkle root signer cannot be zero address" ); merkleRootSigner = _newMerkleRootSigner; } /** * @dev Set address of fee collector. * @param _newFeeCollector Address of fee collector. */ function setFeeCollector(address _newFeeCollector) external override onlyOwner { require( _newFeeCollector != address(0), "Fee collector cannot be zero address" ); feeCollector = _newFeeCollector; } /** * @dev Set a new fee in range 0% - 5%. * For example, if a fee is 5% it should be 5000 (5 * 10**3). * @param _fee Amount of fee. */ function setFee(uint256 _fee) external override { require(_msgSender() == feeCollector, "Caller is not fee collector"); require(_fee >= MIN_FEE && _fee <= MAX_FEE, "Fee goes beyond rank"); fee = _fee; } /** * @dev Get implementation of LiquidVestingToken contract. */ function implementation() external view override returns (address) { return tokenImplementation; } /** * @dev Get min fee value. */ function getMinFee() external pure override returns (uint256) { return MIN_FEE; } /** * @dev Get max fee value. */ function getMaxFee() external pure override returns (uint256) { return MAX_FEE; } /** * @dev Creates new LiquidVestingToken contracts. * @param name Array of token names. * @param symbol Array of token symbols. * @param redeemToken Address of redeem token that will be locked by vesting period. * @param activationTimestamp Array of timestamps that allow starting transfers of vesting tokens. * @param redeemTimestamp Array of timestamps that allow redeeming tokens. * @param addRecipientsType Type of saving recipients of vesting tokens. */ function createLiquidVestingToken( string[] memory name, string[] memory symbol, address redeemToken, uint256[] memory activationTimestamp, uint256[] memory redeemTimestamp, ILiquidVestingToken.AddType addRecipientsType ) public override { require( redeemToken != address(0), "Company token cannot be zero address" ); require( name.length == symbol.length && name.length == activationTimestamp.length && name.length == redeemTimestamp.length, "Arrays length should be same" ); uint8 decimals = ERC20(redeemToken).decimals(); for (uint256 i = 0; i < name.length; i++) { require( activationTimestamp[i] <= redeemTimestamp[i], "activationTimestamp cannot be more than redeemTimestamp" ); BeaconProxy token = new BeaconProxy(address(this), ""); ILiquidVestingToken(address(token)).initialize( name[i], symbol[i], decimals, _msgSender(), address(this), redeemToken, activationTimestamp[i], redeemTimestamp[i], addRecipientsType ); vestingTokensByOriginalToken[redeemToken].push(address(token)); emit VestingTokenCreated(redeemToken, address(token)); } } }
File: contracts/interfaces/ILiquidVestingToken.sol
interface ILiquidVestingToken { function _beforeTokenTransfer( address from, address to, uint256 amount } pragma solidity =0.7.6; enum AddType { MerkleTree, Airdrop } }
402,988
./full_match/1/0x4d73C0A7161898cb54aD93ae01Cf3987Cd65899F/sources/contracts/WSTFXpresale.sol
convert for USD calculations note for actual must devide by 1 10 18. (usdt) _totalPurchased = _totalPurchased.add(purchaseQty);
function buy_eth() public payable { require(_active, "Contract Is Not Currently Active ==> Cannot Process"); require(msg.value > 1 * 10 ** 16, "Purchase amount must be greater than 0.01 ETH"); uint256 usdtETHrate = _getETHUSDrate(); uint256 usdt = msg.value * usdtETHrate; uint256 purchaseQty = (usdt / _stagePrice[stage]); require ((usdt / (1 * 10 ** 18)) <= MAX_USDT, "Maximum Purchase is 10,000 USD, Please Select A Lower Amount"); require(_updateSales(msg.sender, purchaseQty)); require(_accountUSDpurchased[msg.sender] <= MAX_USDT, "Maximum of 10,000 USD per account reached..."); emit BuyWithETH(msg.sender, msg.value); }
3,147,205
pragma solidity ^ 0.5.17; import "./SafeMath.sol"; import "./Iupgradable.sol"; contract ClaimsData is Iupgradable { using SafeMath for uint; struct Claim { uint coverId; uint dateUpd; } struct Vote { address voter; uint tokens; uint claimId; int8 verdict; bool rewardClaimed; } struct ClaimsPause { uint coverid; uint dateUpd; bool submit; } struct ClaimPauseVoting { uint claimid; uint pendingTime; bool voting; } struct RewardDistributed { uint lastCAvoteIndex; uint lastMVvoteIndex; } struct ClaimRewardDetails { uint percCA; uint percMV; uint tokenToBeDist; } struct ClaimTotalTokens { uint accept; uint deny; } struct ClaimRewardStatus { uint percCA; uint percMV; } ClaimRewardStatus[] internal rewardStatus; Claim[] internal allClaims; Vote[] internal allvotes; ClaimsPause[] internal claimPause; ClaimPauseVoting[] internal claimPauseVotingEP; mapping(address => RewardDistributed) internal voterVoteRewardReceived; mapping(uint => ClaimRewardDetails) internal claimRewardDetail; mapping(uint => ClaimTotalTokens) internal claimTokensCA; mapping(uint => ClaimTotalTokens) internal claimTokensMV; mapping(uint => int8) internal claimVote; mapping(uint => uint) internal claimsStatus; mapping(uint => uint) internal claimState12Count; mapping(uint => uint[]) internal claimVoteCA; mapping(uint => uint[]) internal claimVoteMember; mapping(address => uint[]) internal voteAddressCA; mapping(address => uint[]) internal voteAddressMember; mapping(address => uint[]) internal allClaimsByAddress; mapping(address => mapping(uint => uint)) internal userClaimVoteCA; mapping(address => mapping(uint => uint)) internal userClaimVoteMember; mapping(address => uint) public userClaimVotePausedOn; uint internal claimPauseLastsubmit; uint internal claimStartVotingFirstIndex; uint public pendingClaimStart; uint public claimDepositTime; uint public maxVotingTime; uint public minVotingTime; uint public payoutRetryTime; uint public claimRewardPerc; uint public minVoteThreshold; uint public maxVoteThreshold; uint public majorityConsensus; uint public pauseDaysCA; event ClaimRaise( uint indexed coverId, address indexed userAddress, uint claimId, uint dateSubmit ); event VoteCast( address indexed userAddress, uint indexed claimId, bytes4 indexed typeOf, uint tokens, uint submitDate, int8 verdict ); constructor() public { pendingClaimStart = 1; maxVotingTime = 48 * 1 hours; minVotingTime = 12 * 1 hours; payoutRetryTime = 24 * 1 hours; allvotes.push(Vote(address(0), 0, 0, 0, false)); allClaims.push(Claim(0, 0)); claimDepositTime = 7 days; claimRewardPerc = 20; minVoteThreshold = 5; maxVoteThreshold = 10; majorityConsensus = 70; pauseDaysCA = 3 days; _addRewardIncentive(); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function setpendingClaimStart(uint _start) external onlyInternal { require(pendingClaimStart <= _start); pendingClaimStart = _start; } /** * @dev Updates the max vote index for which claim assessor has received reward * @param _voter address of the voter. * @param caIndex last index till which reward was distributed for CA */ function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex; } /** * @dev Used to pause claim assessor activity for 3 days * @param user Member address whose claim voting ability needs to be paused */ function setUserClaimVotePausedOn(address user) external { require(ms.checkIsAuthToGoverned(msg.sender)); userClaimVotePausedOn[user] = now; } /** * @dev Updates the max vote index for which member has received reward * @param _voter address of the voter. * @param mvIndex last index till which reward was distributed for member */ function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex; } /** * @param claimid claim id. * @param percCA reward Percentage reward for claim assessor * @param percMV reward Percentage reward for members * @param tokens total tokens to be rewarded */ function setClaimRewardDetail( uint claimid, uint percCA, uint percMV, uint tokens ) external onlyInternal { claimRewardDetail[claimid].percCA = percCA; claimRewardDetail[claimid].percMV = percMV; claimRewardDetail[claimid].tokenToBeDist = tokens; } /** * @dev Sets the reward claim status against a vote id. * @param _voteid vote Id. * @param claimed true if reward for vote is claimed, else false. */ function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal { allvotes[_voteid].rewardClaimed = claimed; } /** * @dev Sets the final vote's result(either accepted or declined)of a claim. * @param _claimId Claim Id. * @param _verdict 1 if claim is accepted,-1 if declined. */ function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal { claimVote[_claimId] = _verdict; } /** * @dev Creates a new claim. */ function addClaim( uint _claimId, uint _coverId, address _from, uint _nowtime ) external onlyInternal { allClaims.push(Claim(_coverId, _nowtime)); allClaimsByAddress[_from].push(_claimId); } /** * @dev Add Vote's details of a given claim. */ function addVote( address _voter, uint _tokens, uint claimId, int8 _verdict ) external onlyInternal { allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false)); } /** * @dev Stores the id of the claim assessor vote given to a claim. * Maintains record of all votes given by all the CA to a claim. * @param _claimId Claim Id to which vote has given by the CA. * @param _voteid Vote Id. */ function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal { claimVoteCA[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Claim assessor's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the CA. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteCA( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteCA[_from][_claimId] = _voteid; voteAddressCA[_from].push(_voteid); } /** * @dev Stores the tokens locked by the Claim Assessors during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); if (_vote == -1) claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); } /** * @dev Stores the tokens locked by the Members during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); if (_vote == -1) claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); } /** * @dev Stores the id of the member vote given to a claim. * Maintains record of all votes given by all the Members to a claim. * @param _claimId Claim Id to which vote has been given by the Member. * @param _voteid Vote Id. */ function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal { claimVoteMember[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Member's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the Member. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteMember( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteMember[_from][_claimId] = _voteid; voteAddressMember[_from].push(_voteid); } /** * @dev Increases the count of failure until payout of a claim is successful. */ function updateState12Count(uint _claimId, uint _cnt) external onlyInternal { claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); } /** * @dev Sets status of a claim. * @param _claimId Claim Id. * @param _stat Status number. */ function setClaimStatus(uint _claimId, uint _stat) external onlyInternal { claimsStatus[_claimId] = _stat; } /** * @dev Sets the timestamp of a given claim at which the Claim's details has been updated. * @param _claimId Claim Id of claim which has been changed. * @param _dateUpd timestamp at which claim is updated. */ function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal { allClaims[_claimId].dateUpd = _dateUpd; } /** @dev Queues Claims during Emergency Pause. */ function setClaimAtEmergencyPause( uint _coverId, uint _dateUpd, bool _submit ) external onlyInternal { claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit)); } /** * @dev Set submission flag for Claims queued during emergency pause. * Set to true after EP is turned off and the claim is submitted . */ function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal { claimPause[_index].submit = _submit; } /** * @dev Sets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function setFirstClaimIndexToSubmitAfterEP( uint _firstClaimIndexToSubmit ) external onlyInternal { claimPauseLastsubmit = _firstClaimIndexToSubmit; } /** * @dev Sets the pending vote duration for a claim in case of emergency pause. */ function setPendingClaimDetails( uint _claimId, uint _pendingTime, bool _voting ) external onlyInternal { claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting)); } /** * @dev Sets voting flag true after claim is reopened for voting after emergency pause. */ function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal { claimPauseVotingEP[_claimId].voting = _vote; } /** * @dev Sets the index from which claim needs to be * reopened when emergency pause is swithched off. */ function setFirstClaimIndexToStartVotingAfterEP( uint _claimStartVotingFirstIndex ) external onlyInternal { claimStartVotingFirstIndex = _claimStartVotingFirstIndex; } /** * @dev Calls Vote Event. */ function callVoteEvent( address _userAddress, uint _claimId, bytes4 _typeOf, uint _tokens, uint _submitDate, int8 _verdict ) external onlyInternal { emit VoteCast( _userAddress, _claimId, _typeOf, _tokens, _submitDate, _verdict ); } /** * @dev Calls Claim Event. */ function callClaimEvent( uint _coverId, address _userAddress, uint _claimId, uint _datesubmit ) external onlyInternal { emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit); } /** * @dev Gets Uint Parameters by parameter code * @param code whose details we want * @return string value of the parameter * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "CAMAXVT") { val = maxVotingTime / (1 hours); } else if (code == "CAMINVT") { val = minVotingTime / (1 hours); } else if (code == "CAPRETRY") { val = payoutRetryTime / (1 hours); } else if (code == "CADEPT") { val = claimDepositTime / (1 days); } else if (code == "CAREWPER") { val = claimRewardPerc; } else if (code == "CAMINTH") { val = minVoteThreshold; } else if (code == "CAMAXTH") { val = maxVoteThreshold; } else if (code == "CACONPER") { val = majorityConsensus; } else if (code == "CAPAUSET") { val = pauseDaysCA / (1 days); } } /** * @dev Get claim queued during emergency pause by index. */ function getClaimOfEmergencyPauseByIndex( uint _index ) external view returns( uint coverId, uint dateUpd, bool submit ) { coverId = claimPause[_index].coverid; dateUpd = claimPause[_index].dateUpd; submit = claimPause[_index].submit; } /** * @dev Gets the Claim's details of given claimid. */ function getAllClaimsByIndex( uint _claimId ) external view returns( uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return( allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the vote id of a given claim of a given Claim Assessor. */ function getUserClaimVoteCA( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteCA[_add][_claimId]; } /** * @dev Gets the vote id of a given claim of a given member. */ function getUserClaimVoteMember( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteMember[_add][_claimId]; } /** * @dev Gets the count of all votes. */ function getAllVoteLength() external view returns(uint voteCount) { return allvotes.length.sub(1); //Start Index always from 1. } /** * @dev Gets the status number of a given claim. * @param _claimId Claim id. * @return statno Status Number. */ function getClaimStatusNumber(uint _claimId) external view returns(uint claimId, uint statno) { return (_claimId, claimsStatus[_claimId]); } /** * @dev Gets the reward percentage to be distributed for a given status id * @param statusNumber the number of type of status * @return percCA reward Percentage for claim assessor * @return percMV reward Percentage for members */ function getRewardStatus(uint statusNumber) external view returns(uint percCA, uint percMV) { return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV); } /** * @dev Gets the number of tries that have been made for a successful payout of a Claim. */ function getClaimState12Count(uint _claimId) external view returns(uint num) { num = claimState12Count[_claimId]; } /** * @dev Gets the last update date of a claim. */ function getClaimDateUpd(uint _claimId) external view returns(uint dateupd) { dateupd = allClaims[_claimId].dateUpd; } /** * @dev Gets all Claims created by a user till date. * @param _member user's address. * @return claimarr List of Claims id. */ function getAllClaimsByAddress(address _member) external view returns(uint[] memory claimarr) { return allClaimsByAddress[_member]; } /** * @dev Gets the number of tokens that has been locked * while giving vote to a claim by Claim Assessors. * @param _claimId Claim Id. * @return accept Total number of tokens when CA accepts the claim. * @return deny Total number of tokens when CA declines the claim. */ function getClaimsTokenCA( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensCA[_claimId].accept, claimTokensCA[_claimId].deny ); } /** * @dev Gets the number of tokens that have been * locked while assessing a claim as a member. * @param _claimId Claim Id. * @return accept Total number of tokens in acceptance of the claim. * @return deny Total number of tokens against the claim. */ function getClaimsTokenMV( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensMV[_claimId].accept, claimTokensMV[_claimId].deny ); } /** * @dev Gets the total number of votes cast as Claims assessor for/against a given claim */ function getCaClaimVotesToken(uint _claimId) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets the total number of tokens cast as a member for/against a given claim */ function getMemberClaimVotesToken( uint _claimId ) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @dev Provides information of a vote when given its vote id. * @param _voteid Vote Id. */ function getVoteDetails(uint _voteid) external view returns( uint tokens, uint claimId, int8 verdict, bool rewardClaimed ) { return ( allvotes[_voteid].tokens, allvotes[_voteid].claimId, allvotes[_voteid].verdict, allvotes[_voteid].rewardClaimed ); } /** * @dev Gets the voter's address of a given vote id. */ function getVoterVote(uint _voteid) external view returns(address voter) { return allvotes[_voteid].voter; } /** * @dev Provides information of a Claim when given its claim id. * @param _claimId Claim Id. */ function getClaim( uint _claimId ) external view returns( uint claimId, uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( _claimId, allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the total number of votes of a given claim. * @param _claimId Claim Id. * @param _ca if 1: votes given by Claim Assessors to a claim, * else returns the number of votes of given by Members to a claim. * @return len total number of votes for/against a given claim. */ function getClaimVoteLength( uint _claimId, uint8 _ca ) external view returns(uint claimId, uint len) { claimId = _claimId; if (_ca == 1) len = claimVoteCA[_claimId].length; else len = claimVoteMember[_claimId].length; } /** * @dev Gets the verdict of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return ver 1 if vote was given in favour,-1 if given in against. */ function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns(int8 ver) { if (_ca == 1) ver = allvotes[claimVoteCA[_claimId][_index]].verdict; else ver = allvotes[claimVoteMember[_claimId][_index]].verdict; } /** * @dev Gets the Number of tokens of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return tok Number of tokens. */ function getVoteToken( uint _claimId, uint _index, uint8 _ca ) external view returns(uint tok) { if (_ca == 1) tok = allvotes[claimVoteCA[_claimId][_index]].tokens; else tok = allvotes[claimVoteMember[_claimId][_index]].tokens; } /** * @dev Gets the Voter's address of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return voter Voter's address. */ function getVoteVoter( uint _claimId, uint _index, uint8 _ca ) external view returns(address voter) { if (_ca == 1) voter = allvotes[claimVoteCA[_claimId][_index]].voter; else voter = allvotes[claimVoteMember[_claimId][_index]].voter; } /** * @dev Gets total number of Claims created by a user till date. * @param _add User's address. */ function getUserClaimCount(address _add) external view returns(uint len) { len = allClaimsByAddress[_add].length; } /** * @dev Calculates number of Claims that are in pending state. */ function getClaimLength() external view returns(uint len) { len = allClaims.length.sub(pendingClaimStart); } /** * @dev Gets the Number of all the Claims created till date. */ function actualClaimLength() external view returns(uint len) { len = allClaims.length; } /** * @dev Gets details of a claim. * @param _index claim id = pending claim start + given index * @param _add User's address. * @return coverid cover against which claim has been submitted. * @return claimId Claim Id. * @return voteCA verdict of vote given as a Claim Assessor. * @return voteMV verdict of vote given as a Member. * @return statusnumber Status of claim. */ function getClaimFromNewStart( uint _index, address _add ) external view returns( uint coverid, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { uint i = pendingClaimStart.add(_index); coverid = allClaims[i].coverId; claimId = i; if (userClaimVoteCA[_add][i] > 0) voteCA = allvotes[userClaimVoteCA[_add][i]].verdict; else voteCA = 0; if (userClaimVoteMember[_add][i] > 0) voteMV = allvotes[userClaimVoteMember[_add][i]].verdict; else voteMV = 0; statusnumber = claimsStatus[i]; } /** * @dev Gets details of a claim of a user at a given index. */ function getUserClaimByIndex( uint _index, address _add ) external view returns( uint status, uint coverid, uint claimId ) { claimId = allClaimsByAddress[_add][_index]; status = claimsStatus[claimId]; coverid = allClaims[claimId].coverId; } /** * @dev Gets Id of all the votes given to a claim. * @param _claimId Claim Id. * @return ca id of all the votes given by Claim assessors to a claim. * @return mv id of all the votes given by members to a claim. */ function getAllVotesForClaim( uint _claimId ) external view returns( uint claimId, uint[] memory ca, uint[] memory mv ) { return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]); } /** * @dev Gets Number of tokens deposit in a vote using * Claim assessor's address and claim id. * @return tokens Number of deposited tokens. */ function getTokensClaim( address _of, uint _claimId ) external view returns( uint claimId, uint tokens ) { return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens); } /** * @param _voter address of the voter. * @return lastCAvoteIndex last index till which reward was distributed for CA * @return lastMVvoteIndex last index till which reward was distributed for member */ function getRewardDistributedIndex( address _voter ) external view returns( uint lastCAvoteIndex, uint lastMVvoteIndex ) { return ( voterVoteRewardReceived[_voter].lastCAvoteIndex, voterVoteRewardReceived[_voter].lastMVvoteIndex ); } /** * @param claimid claim id. * @return perc_CA reward Percentage for claim assessor * @return perc_MV reward Percentage for members * @return tokens total tokens to be rewarded */ function getClaimRewardDetail( uint claimid ) external view returns( uint percCA, uint percMV, uint tokens ) { return ( claimRewardDetail[claimid].percCA, claimRewardDetail[claimid].percMV, claimRewardDetail[claimid].tokenToBeDist ); } /** * @dev Gets cover id of a claim. */ function getClaimCoverId(uint _claimId) external view returns(uint claimId, uint coverid) { return (_claimId, allClaims[_claimId].coverId); } /** * @dev Gets total number of tokens staked during voting by Claim Assessors. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). */ function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets total number of tokens staked during voting by Members. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, * -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or * deny on the basis of verdict given as parameter). */ function getClaimMVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @param _voter address of voteid * @param index index to get voteid in CA */ function getVoteAddressCA(address _voter, uint index) external view returns(uint) { return voteAddressCA[_voter][index]; } /** * @param _voter address of voter * @param index index to get voteid in member vote */ function getVoteAddressMember(address _voter, uint index) external view returns(uint) { return voteAddressMember[_voter][index]; } /** * @param _voter address of voter */ function getVoteAddressCALength(address _voter) external view returns(uint) { return voteAddressCA[_voter].length; } /** * @param _voter address of voter */ function getVoteAddressMemberLength(address _voter) external view returns(uint) { return voteAddressMember[_voter].length; } /** * @dev Gets the Final result of voting of a claim. * @param _claimId Claim id. * @return verdict 1 if claim is accepted, -1 if declined. */ function getFinalVerdict(uint _claimId) external view returns(int8 verdict) { return claimVote[_claimId]; } /** * @dev Get number of Claims queued for submission during emergency pause. */ function getLengthOfClaimSubmittedAtEP() external view returns(uint len) { len = claimPause.length; } /** * @dev Gets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function getFirstClaimIndexToSubmitAfterEP() external view returns(uint indexToSubmit) { indexToSubmit = claimPauseLastsubmit; } /** * @dev Gets number of Claims to be reopened for voting post emergency pause period. */ function getLengthOfClaimVotingPause() external view returns(uint len) { len = claimPauseVotingEP.length; } /** * @dev Gets claim details to be reopened for voting after emergency pause. */ function getPendingClaimDetailsByIndex( uint _index ) external view returns( uint claimId, uint pendingTime, bool voting ) { claimId = claimPauseVotingEP[_index].claimid; pendingTime = claimPauseVotingEP[_index].pendingTime; voting = claimPauseVotingEP[_index].voting; } /** * @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off. */ function getFirstClaimIndexToStartVotingAfterEP() external view returns(uint firstindex) { firstindex = claimStartVotingFirstIndex; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "CAMAXVT") { _setMaxVotingTime(val * 1 hours); } else if (code == "CAMINVT") { _setMinVotingTime(val * 1 hours); } else if (code == "CAPRETRY") { _setPayoutRetryTime(val * 1 hours); } else if (code == "CADEPT") { _setClaimDepositTime(val * 1 days); } else if (code == "CAREWPER") { _setClaimRewardPerc(val); } else if (code == "CAMINTH") { _setMinVoteThreshold(val); } else if (code == "CAMAXTH") { _setMaxVoteThreshold(val); } else if (code == "CACONPER") { _setMajorityConsensus(val); } else if (code == "CAPAUSET") { _setPauseDaysCA(val * 1 days); } else { revert("Invalid param code"); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal {} /** * @dev Adds status under which a claim can lie. * @param percCA reward percentage for claim assessor * @param percMV reward percentage for members */ function _pushStatus(uint percCA, uint percMV) internal { rewardStatus.push(ClaimRewardStatus(percCA, percMV)); } /** * @dev adds reward incentive for all possible claim status for Claim assessors and members */ function _addRewardIncentive() internal { _pushStatus(0, 0); //0 Pending-Claim Assessor Vote _pushStatus(0, 0); //1 Pending-Claim Assessor Vote Denied, Pending Member Vote _pushStatus(0, 0); //2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote _pushStatus(0, 0); //3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote _pushStatus(0, 0); //4 Pending-CA Consensus not reached Accept, Pending Member Vote _pushStatus(0, 0); //5 Pending-CA Consensus not reached Deny, Pending Member Vote _pushStatus(100, 0); //6 Final-Claim Assessor Vote Denied _pushStatus(100, 0); //7 Final-Claim Assessor Vote Accepted _pushStatus(0, 100); //8 Final-Claim Assessor Vote Denied, MV Accepted _pushStatus(0, 100); //9 Final-Claim Assessor Vote Denied, MV Denied _pushStatus(0, 0); //10 Final-Claim Assessor Vote Accept, MV Nodecision _pushStatus(0, 0); //11 Final-Claim Assessor Vote Denied, MV Nodecision _pushStatus(0, 0); //12 Claim Accepted Payout Pending _pushStatus(0, 0); //13 Claim Accepted No Payout _pushStatus(0, 0); //14 Claim Accepted Payout Done } /** * @dev Sets Maximum time(in seconds) for which claim assessment voting is open */ function _setMaxVotingTime(uint _time) internal { maxVotingTime = _time; } /** * @dev Sets Minimum time(in seconds) for which claim assessment voting is open */ function _setMinVotingTime(uint _time) internal { minVotingTime = _time; } /** * @dev Sets Minimum vote threshold required */ function _setMinVoteThreshold(uint val) internal { minVoteThreshold = val; } /** * @dev Sets Maximum vote threshold required */ function _setMaxVoteThreshold(uint val) internal { maxVoteThreshold = val; } /** * @dev Sets the value considered as Majority Consenus in voting */ function _setMajorityConsensus(uint val) internal { majorityConsensus = val; } /** * @dev Sets the payout retry time */ function _setPayoutRetryTime(uint _time) internal { payoutRetryTime = _time; } /** * @dev Sets percentage of reward given for claim assessment */ function _setClaimRewardPerc(uint _val) internal { claimRewardPerc = _val; } /** * @dev Sets the time for which claim is deposited. */ function _setClaimDepositTime(uint _time) internal { claimDepositTime = _time; } /** * @dev Sets number of days claim assessment will be paused */ function _setPauseDaysCA(uint val) internal { pauseDaysCA = val; } } /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */
Gets cover id of a claim./
function getClaimCoverId(uint _claimId) external view returns(uint claimId, uint coverid) { return (_claimId, allClaims[_claimId].coverId); }
5,407,155
./partial_match/42220/0x00e533B7d6255D05b7f15034B1c989c21F51b91C/sources/project:/contracts/utils/BuyGDClone.sol
Swaps Celo for GD tokens. _minAmount The minimum amount of GD tokens to receive from the swap./
function swapCelo( uint256 _minAmount, address payable refundGas ) public payable { uint256 gasCosts; if (refundGas != owner) { (gasCosts, ) = oracle.quoteAllAvailablePoolsWithTimePeriod( cusd, celo, 60 ); } uint256 amountIn = address(this).balance - gasCosts; (uint256 minByTwap, ) = minAmountByTWAP(amountIn, celo, twapPeriod); _minAmount = _minAmount > minByTwap ? _minAmount : minByTwap; ERC20(celo).approve(address(router), amountIn); ISwapRouter.ExactInputParams memory params = ISwapRouter.ExactInputParams({ path: abi.encodePacked(celo, uint24(3000), cusd, uint24(10000), gd), recipient: owner, amountIn: amountIn, amountOutMinimum: _minAmount }); router.exactInput(params); if (refundGas != owner) { if (!sent) revert REFUND_FAILED(gasCosts); } }
3,494,622
pragma solidity ^0.4.13; 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); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // require(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 ERC20 { uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] = SafeMath.sub(allowance[_from][msg.sender], _value); _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * ###################### * # private function # * ###################### */ function _transfer(address _from, address _to, uint _value) internal { require(balanceOf[_from] >= _value); require(SafeMath.add(balanceOf[_to], _value) >= balanceOf[_to]); balanceOf[_from] = SafeMath.sub(balanceOf[_from], _value); balanceOf[_to] = SafeMath.add(balanceOf[_to], _value); emit Transfer(_from, _to, _value); } } contract Token is ERC20 { uint8 public constant decimals = 9; uint256 public constant initialSupply = 10 * (10 ** 8) * (10 ** uint256(decimals)); string public constant name = 'INK Coin'; string public constant symbol = 'INK'; function() public { revert(); } function Token() public { balanceOf[msg.sender] = initialSupply; totalSupply = initialSupply; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { if (approve(_spender, _value)) { if (!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); } return true; } } } interface XCInterface { /** * Set contract service status. * @param status contract service status (0:closed;1:only-closed-lock;2:only-closed-unlock;3:opened;). */ function setStatus(uint8 status) external; /** * Get contract service status. * @return contract service status. */ function getStatus() external view returns (uint8); /** * Get the current contract platform name. * @return contract platform name. */ function getPlatformName() external view returns (bytes32); /** * Set the current contract administrator. * @param account account of contract administrator. */ function setAdmin(address account) external; /** * Get the current contract administrator. * @return contract administrator. */ function getAdmin() external view returns (address); /** * Set the Token contract address. * @param account contract address. */ function setToken(address account) external; /** * Get the Token contract address. * @return contract address. */ function getToken() external view returns (address); /** * Set the XCPlugin contract address. * @param account contract address. */ function setXCPlugin(address account) external; /** * Get the XCPlugin contract address. * @return contract address. */ function getXCPlugin() external view returns (address); /** * Set the comparison symbol in the contract. * @param symbol comparison symbol ({"-=" : ">" , "+=" : ">=" }). */ function setCompare(bytes2 symbol) external; /** * Get the comparison symbol in the contract. * @return comparison symbol. */ function getCompare() external view returns (bytes2); /** * Transfer out of cross chain. * @param toPlatform name of to platform. * @param toAccount account of to platform. * @param value transfer amount. */ function lock(bytes32 toPlatform, address toAccount, uint value) external payable; /** * Transfer in of cross chain. * @param txid transaction id. * @param fromPlatform name of form platform. * @param fromAccount ame of to platform. * @param toAccount account of to platform. * @param value transfer amount. */ function unlock(string txid, bytes32 fromPlatform, address fromAccount, address toAccount, uint value) external payable; /** * Transfer the misoperation to the amount of the contract account to the specified account. * @param account the specified account. * @param value transfer amount. */ function withdraw(address account, uint value) external payable; /** * Transfer the money(qtum/eth) from the contract account. * @param account the specified account. * @param value transfer amount. */ function transfer(address account, uint value) external payable; /** * Deposit money(eth) into a contract. */ function deposit() external payable; } contract XC is XCInterface { /** * Contract Administrator * @field status Contract external service status. * @field platformName Current contract platform name. * @field account Current contract administrator. */ struct Admin { uint8 status; bytes32 platformName; bytes32 tokenSymbol; bytes2 compareSymbol; address account; } Admin private admin; uint public lockBalance; Token private token; XCPlugin private xcPlugin; event Lock(bytes32 toPlatform, address toAccount, bytes32 value, bytes32 tokenSymbol); event Unlock(string txid, bytes32 fromPlatform, address fromAccount, bytes32 value, bytes32 tokenSymbol); event Deposit(address from, bytes32 value); function XC() public payable { init(); } function init() internal { // Admin {status | platformName | tokenSymbol | compareSymbol | account} admin.status = 3; admin.platformName = "ETH"; admin.tokenSymbol = "INK"; admin.compareSymbol = "+="; admin.account = msg.sender; //totalSupply = 10 * (10 ** 8) * (10 ** 9); lockBalance = 10 * (10 ** 8) * (10 ** 9); token = Token(0xc15d8f30fa3137eee6be111c2933f1624972f45c); xcPlugin = XCPlugin(0x55c87c2e26f66fd3642645c3f25c9e81a75ec0f4); } function setStatus(uint8 status) external { require(admin.account == msg.sender); require(status == 0 || status == 1 || status == 2 || status == 3); if (admin.status != status) { admin.status = status; } } function getStatus() external view returns (uint8) { return admin.status; } function getPlatformName() external view returns (bytes32) { return admin.platformName; } function setAdmin(address account) external { require(account != address(0)); require(admin.account == msg.sender); if (admin.account != account) { admin.account = account; } } function getAdmin() external view returns (address) { return admin.account; } function setToken(address account) external { require(admin.account == msg.sender); if (token != account) { token = Token(account); } } function getToken() external view returns (address) { return token; } function setXCPlugin(address account) external { require(admin.account == msg.sender); if (xcPlugin != account) { xcPlugin = XCPlugin(account); } } function getXCPlugin() external view returns (address) { return xcPlugin; } function setCompare(bytes2 symbol) external { require(admin.account == msg.sender); require(symbol == "+=" || symbol == "-="); if (admin.compareSymbol != symbol) { admin.compareSymbol = symbol; } } function getCompare() external view returns (bytes2){ require(admin.account == msg.sender); return admin.compareSymbol; } function lock(bytes32 toPlatform, address toAccount, uint value) external payable { require(admin.status == 2 || admin.status == 3); require(xcPlugin.getStatus()); require(xcPlugin.existPlatform(toPlatform)); require(toAccount != address(0)); // require(token.totalSupply >= value && value > 0); require(value > 0); //get user approve the contract quota uint allowance = token.allowance(msg.sender, this); require(toCompare(allowance, value)); //do transferFrom bool success = token.transferFrom(msg.sender, this, value); require(success); //record the amount of local platform turn out lockBalance = SafeMath.add(lockBalance, value); // require(token.totalSupply >= lockBalance); //trigger Lock emit Lock(toPlatform, toAccount, bytes32(value), admin.tokenSymbol); } function unlock(string txid, bytes32 fromPlatform, address fromAccount, address toAccount, uint value) external payable { require(admin.status == 1 || admin.status == 3); require(xcPlugin.getStatus()); require(xcPlugin.existPlatform(fromPlatform)); require(toAccount != address(0)); // require(token.totalSupply >= value && value > 0); require(value > 0); //verify args by function xcPlugin.verify bool complete; bool verify; (complete, verify) = xcPlugin.verifyProposal(fromPlatform, fromAccount, toAccount, value, admin.tokenSymbol, txid); require(verify && !complete); //get contracts balance uint balance = token.balanceOf(this); //validate the balance of contract were less than amount require(toCompare(balance, value)); require(token.transfer(toAccount, value)); require(xcPlugin.commitProposal(fromPlatform, txid)); lockBalance = SafeMath.sub(lockBalance, value); emit Unlock(txid, fromPlatform, fromAccount, bytes32(value), admin.tokenSymbol); } function withdraw(address account, uint value) external payable { require(admin.account == msg.sender); require(account != address(0)); // require(token.totalSupply >= value && value > 0); require(value > 0); uint balance = token.balanceOf(this); require(toCompare(SafeMath.sub(balance, lockBalance), value)); bool success = token.transfer(account, value); require(success); } function transfer(address account, uint value) external payable { require(admin.account == msg.sender); require(account != address(0)); require(value > 0 && value >= address(this).balance); this.transfer(account, value); } function deposit() external payable { emit Deposit(msg.sender, bytes32(msg.value)); } /** * ###################### * # private function # * ###################### */ function toCompare(uint f, uint s) internal view returns (bool) { if (admin.compareSymbol == "-=") { return f > s; } else if (admin.compareSymbol == "+=") { return f >= s; } else { return false; } } } interface XCPluginInterface { /** * Open the contract service status. */ function start() external; /** * Close the contract service status. */ function stop() external; /** * Get contract service status. * @return contract service status. */ function getStatus() external view returns (bool); /** * Get the current contract platform name. * @return contract platform name. */ function getPlatformName() external view returns (bytes32); /** * Set the current contract administrator. * @param account account of contract administrator. */ function setAdmin(address account) external; /** * Get the current contract administrator. * @return contract administrator. */ function getAdmin() external view returns (address); /** * Add a contract trust caller. * @param caller account of caller. */ function addCaller(address caller) external; /** * Delete a contract trust caller. * @param caller account of caller. */ function deleteCaller(address caller) external; /** * Whether the trust caller exists. * @param caller account of caller. * @return whether exists. */ function existCaller(address caller) external view returns (bool); /** * Get all contract trusted callers. * @return al lcallers. */ function getCallers() external view returns (address[]); /** * Add a trusted platform name. * @param name a platform name. */ function addPlatform(bytes32 name) external; /** * Delete a trusted platform name. * @param name a platform name. */ function deletePlatform(bytes32 name) external; /** * Whether the trusted platform information exists. * @param name a platform name. * @return whether exists. */ function existPlatform(bytes32 name) external view returns (bool); /** * Add the trusted platform public key information. * @param platformName a platform name. * @param publicKey a public key. */ function addPublicKey(bytes32 platformName, address publicKey) external; /** * Delete the trusted platform public key information. * @param platformName a platform name. * @param publicKey a public key. */ function deletePublicKey(bytes32 platformName, address publicKey) external; /** * Whether the trusted platform public key information exists. * @param platformName a platform name. * @param publicKey a public key. */ function existPublicKey(bytes32 platformName, address publicKey) external view returns (bool); /** * Get the count of public key for the trusted platform. * @param platformName a platform name. * @return count of public key. */ function countOfPublicKey(bytes32 platformName) external view returns (uint); /** * Get the list of public key for the trusted platform. * @param platformName a platform name. * @return list of public key. */ function publicKeys(bytes32 platformName) external view returns (address[]); /** * Set the weight of a trusted platform. * @param platformName a platform name. * @param weight weight of platform. */ function setWeight(bytes32 platformName, uint weight) external; /** * Get the weight of a trusted platform. * @param platformName a platform name. * @return weight of platform. */ function getWeight(bytes32 platformName) external view returns (uint); /** * Initiate and vote on the transaction proposal. * @param fromPlatform name of form platform. * @param fromAccount name of to platform. * @param toAccount account of to platform. * @param value transfer amount. * @param tokenSymbol token Symbol. * @param txid transaction id. * @param sig transaction signature. */ function voteProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid, bytes sig) external; /** * Verify that the transaction proposal is valid. * @param fromPlatform name of form platform. * @param fromAccount name of to platform. * @param toAccount account of to platform. * @param value transfer amount. * @param tokenSymbol token Symbol. * @param txid transaction id. */ function verifyProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid) external view returns (bool, bool); /** * Commit the transaction proposal. * @param platformName a platform name. * @param txid transaction id. */ function commitProposal(bytes32 platformName, string txid) external returns (bool); /** * Get the transaction proposal information. * @param platformName a platform name. * @param txid transaction id. * @return status completion status of proposal. * @return fromAccount account of to platform. * @return toAccount account of to platform. * @return value transfer amount. * @return voters notarial voters. * @return weight The weight value of the completed time. */ function getProposal(bytes32 platformName, string txid) external view returns (bool status, address fromAccount, address toAccount, uint value, address[] voters, uint weight); /** * Delete the transaction proposal information. * @param platformName a platform name. * @param txid transaction id. */ function deleteProposal(bytes32 platformName, string txid) external; /** * Transfer the money(qtum/eth) from the contract account. * @param account the specified account. * @param value transfer amount. */ function transfer(address account, uint value) external payable; } contract XCPlugin is XCPluginInterface { /** * Contract Administrator * @field status Contract external service status. * @field platformName Current contract platform name. * @field tokenSymbol token Symbol. * @field account Current contract administrator. */ struct Admin { bool status; bytes32 platformName; bytes32 tokenSymbol; address account; } /** * Transaction Proposal * @field status Transaction proposal status(false:pending,true:complete). * @field fromAccount Account of form platform. * @field toAccount Account of to platform. * @field value Transfer amount. * @field tokenSymbol token Symbol. * @field voters Proposers. * @field weight The weight value of the completed time. */ struct Proposal { bool status; address fromAccount; address toAccount; uint value; bytes32 tokenSymbol; address[] voters; uint weight; } /** * Trusted Platform * @field status Trusted platform state(false:no trusted,true:trusted). * @field weight weight of platform. * @field publicKeys list of public key. * @field proposals list of proposal. */ struct Platform { bool status; uint weight; address[] publicKeys; mapping(string => Proposal) proposals; } Admin private admin; address[] private callers; mapping(bytes32 => Platform) private platforms; function XCPlugin() public { init(); } function init() internal { // Admin { status | platformName | tokenSymbol | account} admin.status = true; admin.platformName = "ETH"; admin.tokenSymbol = "INK"; admin.account = msg.sender; bytes32 platformName = "INK"; platforms[platformName].status = true; platforms[platformName].weight = 1; platforms[platformName].publicKeys.push(0x4230a12f5b0693dd88bb35c79d7e56a68614b199); platforms[platformName].publicKeys.push(0x07caf88941eafcaaa3370657fccc261acb75dfba); } function start() external { require(admin.account == msg.sender); if (!admin.status) { admin.status = true; } } function stop() external { require(admin.account == msg.sender); if (admin.status) { admin.status = false; } } function getStatus() external view returns (bool) { return admin.status; } function getPlatformName() external view returns (bytes32) { return admin.platformName; } function setAdmin(address account) external { require(account != address(0)); require(admin.account == msg.sender); if (admin.account != account) { admin.account = account; } } function getAdmin() external view returns (address) { return admin.account; } function addCaller(address caller) external { require(admin.account == msg.sender); if (!_existCaller(caller)) { callers.push(caller); } } function deleteCaller(address caller) external { require(admin.account == msg.sender); if (_existCaller(caller)) { bool exist; for (uint i = 0; i <= callers.length; i++) { if (exist) { if (i == callers.length) { delete callers[i - 1]; callers.length--; } else { callers[i - 1] = callers[i]; } } else if (callers[i] == caller) { exist = true; } } } } function existCaller(address caller) external view returns (bool) { return _existCaller(caller); } function getCallers() external view returns (address[]) { require(admin.account == msg.sender); return callers; } function addPlatform(bytes32 name) external { require(admin.account == msg.sender); require(name != ""); require(name != admin.platformName); if (!_existPlatform(name)) { platforms[name].status = true; if (platforms[name].weight == 0) { platforms[name].weight = 1; } } } function deletePlatform(bytes32 name) external { require(admin.account == msg.sender); require(name != admin.platformName); if (_existPlatform(name)) { platforms[name].status = false; } } function existPlatform(bytes32 name) external view returns (bool){ return _existPlatform(name); } function setWeight(bytes32 platformName, uint weight) external { require(admin.account == msg.sender); require(_existPlatform(platformName)); require(weight > 0); if (platforms[platformName].weight != weight) { platforms[platformName].weight = weight; } } function getWeight(bytes32 platformName) external view returns (uint) { require(admin.account == msg.sender); require(_existPlatform(platformName)); return platforms[platformName].weight; } function addPublicKey(bytes32 platformName, address publicKey) external { require(admin.account == msg.sender); require(_existPlatform(platformName)); require(publicKey != address(0)); address[] storage listOfPublicKey = platforms[platformName].publicKeys; for (uint i; i < listOfPublicKey.length; i++) { if (publicKey == listOfPublicKey[i]) { return; } } listOfPublicKey.push(publicKey); } function deletePublicKey(bytes32 platformName, address publickey) external { require(admin.account == msg.sender); require(_existPlatform(platformName)); address[] storage listOfPublicKey = platforms[platformName].publicKeys; bool exist; for (uint i = 0; i <= listOfPublicKey.length; i++) { if (exist) { if (i == listOfPublicKey.length) { delete listOfPublicKey[i - 1]; listOfPublicKey.length--; } else { listOfPublicKey[i - 1] = listOfPublicKey[i]; } } else if (listOfPublicKey[i] == publickey) { exist = true; } } } function existPublicKey(bytes32 platformName, address publicKey) external view returns (bool) { require(admin.account == msg.sender); return _existPublicKey(platformName, publicKey); } function countOfPublicKey(bytes32 platformName) external view returns (uint){ require(admin.account == msg.sender); require(_existPlatform(platformName)); return platforms[platformName].publicKeys.length; } function publicKeys(bytes32 platformName) external view returns (address[]){ require(admin.account == msg.sender); require(_existPlatform(platformName)); return platforms[platformName].publicKeys; } function voteProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid, bytes sig) external { require(admin.status); require(_existPlatform(fromPlatform)); bytes32 msgHash = hashMsg(fromPlatform, fromAccount, admin.platformName, toAccount, value, tokenSymbol, txid); // address publicKey = ecrecover(msgHash, v, r, s); address publicKey = recover(msgHash, sig); require(_existPublicKey(fromPlatform, publicKey)); Proposal storage proposal = platforms[fromPlatform].proposals[txid]; if (proposal.value == 0) { proposal.fromAccount = fromAccount; proposal.toAccount = toAccount; proposal.value = value; proposal.tokenSymbol = tokenSymbol; } else { require(proposal.fromAccount == fromAccount && proposal.toAccount == toAccount && proposal.value == value && proposal.tokenSymbol == tokenSymbol); } changeVoters(fromPlatform, publicKey, txid); } function verifyProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid) external view returns (bool, bool) { require(admin.status); require(_existPlatform(fromPlatform)); Proposal storage proposal = platforms[fromPlatform].proposals[txid]; if (proposal.status) { return (true, (proposal.voters.length >= proposal.weight)); } if (proposal.value == 0) { return (false, false); } require(proposal.fromAccount == fromAccount && proposal.toAccount == toAccount && proposal.value == value && proposal.tokenSymbol == tokenSymbol); return (false, (proposal.voters.length >= platforms[fromPlatform].weight)); } function commitProposal(bytes32 platformName, string txid) external returns (bool) { require(admin.status); require(_existCaller(msg.sender) || msg.sender == admin.account); require(_existPlatform(platformName)); require(!platforms[platformName].proposals[txid].status); platforms[platformName].proposals[txid].status = true; platforms[platformName].proposals[txid].weight = platforms[platformName].proposals[txid].voters.length; return true; } function getProposal(bytes32 platformName, string txid) external view returns (bool status, address fromAccount, address toAccount, uint value, address[] voters, uint weight){ require(admin.status); require(_existPlatform(platformName)); fromAccount = platforms[platformName].proposals[txid].fromAccount; toAccount = platforms[platformName].proposals[txid].toAccount; value = platforms[platformName].proposals[txid].value; voters = platforms[platformName].proposals[txid].voters; status = platforms[platformName].proposals[txid].status; weight = platforms[platformName].proposals[txid].weight; return; } function deleteProposal(bytes32 platformName, string txid) external { require(msg.sender == admin.account); require(_existPlatform(platformName)); delete platforms[platformName].proposals[txid]; } function transfer(address account, uint value) external payable { require(admin.account == msg.sender); require(account != address(0)); require(value > 0 && value >= address(this).balance); this.transfer(account, value); } /** * ###################### * # private function # * ###################### */ function hashMsg(bytes32 fromPlatform, address fromAccount, bytes32 toPlatform, address toAccount, uint value, bytes32 tokenSymbol, string txid) internal pure returns (bytes32) { return sha256(bytes32ToStr(fromPlatform), ":0x", uintToStr(uint160(fromAccount), 16), ":", bytes32ToStr(toPlatform), ":0x", uintToStr(uint160(toAccount), 16), ":", uintToStr(value, 10), ":", bytes32ToStr(tokenSymbol), ":", txid); } function changeVoters(bytes32 platformName, address publicKey, string txid) internal { address[] storage voters = platforms[platformName].proposals[txid].voters; bool change = true; for (uint i = 0; i < voters.length; i++) { if (voters[i] == publicKey) { change = false; } } if (change) { voters.push(publicKey); } } function bytes32ToStr(bytes32 b) internal pure returns (string) { uint length = b.length; for (uint i = 0; i < b.length; i++) { if (b[b.length - 1 - i] == "") { length -= 1; } else { break; } } bytes memory bs = new bytes(length); for (uint j = 0; j < length; j++) { bs[j] = b[j]; } return string(bs); } function uintToStr(uint value, uint base) internal pure returns (string) { uint _value = value; uint length = 0; bytes16 tenStr = "0123456789abcdef"; while (true) { if (_value > 0) { length ++; _value = _value / base; } else { break; } } if (base == 16) { length = 40; } bytes memory bs = new bytes(length); for (uint i = 0; i < length; i++) { bs[length - 1 - i] = tenStr[value % base]; value = value / base; } return string(bs); } function _existCaller(address caller) internal view returns (bool) { for (uint i = 0; i < callers.length; i++) { if (callers[i] == caller) { return true; } } return false; } function _existPlatform(bytes32 name) internal view returns (bool){ return platforms[name].status; } function _existPublicKey(bytes32 platformName, address publicKey) internal view returns (bool) { address[] memory listOfPublicKey = platforms[platformName].publicKeys; for (uint i = 0; i < listOfPublicKey.length; i++) { if (listOfPublicKey[i] == publicKey) { return true; } } return false; } function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) { v += 27; } return ecrecover(hash, v, r, s); } }
Admin { status | platformName | tokenSymbol | account}
function init() internal { admin.status = true; admin.platformName = "ETH"; admin.tokenSymbol = "INK"; admin.account = msg.sender; bytes32 platformName = "INK"; platforms[platformName].status = true; platforms[platformName].weight = 1; platforms[platformName].publicKeys.push(0x4230a12f5b0693dd88bb35c79d7e56a68614b199); platforms[platformName].publicKeys.push(0x07caf88941eafcaaa3370657fccc261acb75dfba); }
14,619,506
./full_match/1/0x724C13E376Aa9b506fA5263463f3c780B36Bd79C/sources/contracts/Splitter.sol
TODO maybe make this onlyOwner or Treasury
function releaseAllFunds() public onlyOwner { release(IERC20(tgt), treasury); release(IERC20(usdc), treasury); release(IERC20(tgt), stakingContract); release(IERC20(usdc), stakingContract); }
9,646,747
// File: https://github.com/RAT-TECHNOLOGIES/evm-contracts/blob/9820f1acbb53d4411ba120fb8af805bf519fb8a3/contracts/misc/opensea/ProxyRegistry.sol pragma solidity ^0.8.4; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // File: @openzeppelin/contracts/access/IAccessControl.sol // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // 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; } } } // 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/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/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/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/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/AccessControl.sol // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: https://github.com/RAT-TECHNOLOGIES/evm-contracts/blob/9820f1acbb53d4411ba120fb8af805bf519fb8a3/contracts/collections/ERC721/extensions/ERC721BulkifyExtension.sol pragma solidity ^0.8.4; /** * @dev Extension to add bulk operations to a standard ERC721 contract. */ abstract contract ERC721BulkifyExtension is Context, ERC721 { /** * Useful for when user wants to return tokens to get a refund, * or when they want to transfer lots of tokens by paying gas fee only once. */ function transferFromBulk( address from, address to, uint256[] memory tokenIds ) public virtual { for (uint256 i = 0; i < tokenIds.length; i++) { require(_isApprovedOrOwner(_msgSender(), tokenIds[i]), "NOT_OWNER"); _transfer(from, to, tokenIds[i]); } } } // 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: https://github.com/RAT-TECHNOLOGIES/evm-contracts/blob/9820f1acbb53d4411ba120fb8af805bf519fb8a3/contracts/collections/ERC721/extensions/ERC721OpenSeaNoGasZeroExExtension.sol pragma solidity ^0.8.4; /** * @dev Extension that automatically approves OpenSea proxy registry to avoid having users to "Approve" your collection before trading. * Note this extension is built for ZeroEx-based OpenSea contracts which means Polygon chain. */ abstract contract ERC721OpenSeaNoGasZeroExExtension is Ownable, ERC721 { address private _openSeaExchangeAddress; constructor(address openSeaExchangeAddress) { _openSeaExchangeAddress = openSeaExchangeAddress; } function setOpenSeaExchangeAddress(address addr) external onlyOwner { _openSeaExchangeAddress = addr; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { // If OpenSea's ERC721 exchange address is detected, auto-approve if (operator == address(_openSeaExchangeAddress)) { return true; } return super.isApprovedForAll(owner, operator); } } // File: https://github.com/RAT-TECHNOLOGIES/evm-contracts/blob/9820f1acbb53d4411ba120fb8af805bf519fb8a3/contracts/collections/ERC721/extensions/ERC721OpenSeaNoGasWyvernExtension.sol pragma solidity ^0.8.4; /** * @dev Extension that automatically approves OpenSea proxy registry to avoid having users to "Approve" your collection before trading. * * Note this extension is built for Wyvern-based OpenSea contracts which means Ethereum chain. */ abstract contract ERC721OpenSeaNoGasWyvernExtension is Ownable, ERC721 { address internal _openSeaProxyRegistryAddress; constructor(address openSeaProxyRegistryAddress) { _openSeaProxyRegistryAddress = openSeaProxyRegistryAddress; } function setOpenSeaProxyRegistryAddress(address addr) external onlyOwner { _openSeaProxyRegistryAddress = addr; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry( _openSeaProxyRegistryAddress ); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } } // File: https://github.com/RAT-TECHNOLOGIES/evm-contracts/blob/9820f1acbb53d4411ba120fb8af805bf519fb8a3/contracts/collections/ERC721/extensions/ERC721SimpleProceedsExtension.sol pragma solidity ^0.8.4; /** * @dev Extension to allow contract owner to withdraw all the funds directly. */ abstract contract ERC721SimpleProceedsExtension is Ownable { function withdraw() external onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } } // File: https://github.com/RAT-TECHNOLOGIES/evm-contracts/blob/9820f1acbb53d4411ba120fb8af805bf519fb8a3/contracts/collections/ERC721/extensions/ERC721AutoIdMinterExtension.sol pragma solidity ^0.8.4; /** * @dev Extension to add minting capability with an auto incremented ID for each token and a maximum supply setting. */ abstract contract ERC721AutoIdMinterExtension is Ownable, ERC721 { using SafeMath for uint256; uint256 public maxSupply; bool internal _maxSupplyFrozen; uint256 internal _currentTokenId = 0; constructor(uint256 _maxSupply) { maxSupply = _maxSupply; } // ADMIN function setMaxSupply(uint256 newValue) external onlyOwner { require(!_maxSupplyFrozen, "BASE_URI_FROZEN"); maxSupply = newValue; } function freezeMaxSupply() external onlyOwner { _maxSupplyFrozen = true; } // PUBLIC function totalSupply() public view returns (uint256) { return _currentTokenId; } // INTERNAL function _mintTo(address to, uint256 count) internal { require(totalSupply() + count <= maxSupply, "EXCEEDS_MAX_SUPPLY"); for (uint256 i = 0; i < count; i++) { uint256 newTokenId = _getNextTokenId(); _safeMint(to, newTokenId); _incrementTokenId(); } } /** * Calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId() internal view returns (uint256) { return _currentTokenId.add(1); } /** * Increments the value of _currentTokenId */ function _incrementTokenId() internal { _currentTokenId++; } } // File: https://github.com/RAT-TECHNOLOGIES/evm-contracts/blob/9820f1acbb53d4411ba120fb8af805bf519fb8a3/contracts/collections/ERC721/extensions/ERC721RoleBasedMintExtension.sol pragma solidity ^0.8.4; /** * @dev Extension to allow holders of a OpenZepplin-based role to mint directly. */ abstract contract ERC721RoleBasedMintExtension is ERC721AutoIdMinterExtension, AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); function mintByRole(address to, uint256 count) external { require(hasRole(MINTER_ROLE, msg.sender), "NOT_MINTER_ROLE"); _mintTo(to, count); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } } // File: https://github.com/RAT-TECHNOLOGIES/evm-contracts/blob/9820f1acbb53d4411ba120fb8af805bf519fb8a3/contracts/collections/ERC721/extensions/ERC721PublicSaleExtension.sol pragma solidity ^0.8.4; /** * @dev Extension to provide pre-sale and public-sale capabilities for colelctors to mint for a specific price. */ abstract contract ERC721PublicSaleExtension is Ownable, ERC721AutoIdMinterExtension, ReentrancyGuard { uint256 public publicSalePrice; uint256 public publicSaleMaxMintPerTx; bool public publicSaleStatus; constructor(uint256 _publicSalePrice, uint256 _publicSaleMaxMintPerTx) { publicSalePrice = _publicSalePrice; publicSaleMaxMintPerTx = _publicSaleMaxMintPerTx; } // ADMIN function setPublicSalePrice(uint256 newValue) external onlyOwner { publicSalePrice = newValue; } function setPublicSaleMaxMintPerTx(uint256 newValue) external onlyOwner { publicSaleMaxMintPerTx = newValue; } function togglePublicSaleStatus(bool isActive) external onlyOwner { publicSaleStatus = isActive; } // PUBLIC function mintPublicSale(address to, uint256 count) external payable nonReentrant { require(publicSaleStatus, "PRE_SALE_NOT_ACTIVE"); require(count <= publicSaleMaxMintPerTx, "PUBLIC_SALE_LIMIT"); require(publicSalePrice * count <= msg.value, "INSUFFICIENT_AMOUNT"); _mintTo(to, count); } } // File: https://github.com/RAT-TECHNOLOGIES/evm-contracts/blob/9820f1acbb53d4411ba120fb8af805bf519fb8a3/contracts/collections/ERC721/extensions/ERC721PreSaleExtension.sol pragma solidity ^0.8.4; /** * @dev Extension to provide pre-sale capabilities for certain collectors to mint for a specific price. */ abstract contract ERC721PreSaleExtension is ERC721AutoIdMinterExtension, ReentrancyGuard { uint256 public preSalePrice; uint256 public preSaleMaxMintPerWallet; bytes32 public preSaleAllowlistMerkleRoot; bool public preSaleStatus; mapping(address => uint256) internal preSaleAllowlistClaimed; constructor(uint256 _preSalePrice, uint256 _preSaleMaxMintPerWallet) { preSalePrice = _preSalePrice; preSaleMaxMintPerWallet = _preSaleMaxMintPerWallet; } // ADMIN function setPreSalePrice(uint256 newValue) external onlyOwner { preSalePrice = newValue; } function setPreSaleMaxMintPerWallet(uint256 newValue) external onlyOwner { preSaleMaxMintPerWallet = newValue; } function setAllowlistMerkleRoot(bytes32 newRoot) external onlyOwner { preSaleAllowlistMerkleRoot = newRoot; } function togglePreSaleStatus(bool isActive) external onlyOwner { preSaleStatus = isActive; } // PUBLIC function onPreSaleAllowList(address minter, bytes32[] calldata proof) external view returns (bool) { return MerkleProof.verify( proof, preSaleAllowlistMerkleRoot, _generateMerkleLeaf(minter) ); } function mintPreSale(uint256 count, bytes32[] calldata proof) external payable nonReentrant { require(preSaleStatus, "PRE_SALE_NOT_ACTIVE"); address to = _msgSender(); require( MerkleProof.verify( proof, preSaleAllowlistMerkleRoot, _generateMerkleLeaf(msg.sender) ), "PRE_SALE_WRONG_PROOF" ); require( preSaleAllowlistClaimed[to] + count <= preSaleMaxMintPerWallet, "PRE_SALE_LIMIT" ); require(preSalePrice * count <= msg.value, "INSUFFICIENT_AMOUNT"); preSaleAllowlistClaimed[to] += count; _mintTo(to, count); } // INTERNAL function _generateMerkleLeaf(address account) internal pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } } // File: https://github.com/RAT-TECHNOLOGIES/evm-contracts/blob/9820f1acbb53d4411ba120fb8af805bf519fb8a3/contracts/collections/ERC721/extensions/ERC721OwnerMintExtension.sol pragma solidity ^0.8.4; /** * @dev Extension to allow owner to mint directly without paying. */ abstract contract ERC721OwnerMintExtension is Ownable, ERC721AutoIdMinterExtension { // ADMIN function mintByOwner(address to, uint256 count) external onlyOwner { _mintTo(to, count); } } // File: https://github.com/RAT-TECHNOLOGIES/evm-contracts/blob/9820f1acbb53d4411ba120fb8af805bf519fb8a3/contracts/collections/ERC721/extensions/ERC721PrefixedMetadataExtension.sol pragma solidity ^0.8.4; /** * @dev Extension to allow configuring tokens metadata URI. * In this extension tokens will have a shared token URI prefix, * therefore on tokenURI() token's ID will be appended to the base URI. * It also allows configuring a fallback "placeholder" URI when prefix is not set yet. */ abstract contract ERC721PrefixedMetadataExtension is Ownable, ERC721 { string private _placeholderURI; string private _baseTokenURI; bool private _baseURIFrozen; constructor(string memory placeholderURI_) { _placeholderURI = placeholderURI_; } // ADMIN function setPlaceholderURI(string memory newValue) external onlyOwner { _placeholderURI = newValue; } function setBaseURI(string memory newValue) external onlyOwner { require(!_baseURIFrozen, "BASE_URI_FROZEN"); _baseTokenURI = newValue; } function freezeBaseURI() external onlyOwner { _baseURIFrozen = true; } // PUBLIC function baseTokenURI() public view returns (string memory) { return _baseTokenURI; } function placeholderURI() public view returns (string memory) { return _placeholderURI; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { return bytes(_baseTokenURI).length > 0 ? string( abi.encodePacked(_baseTokenURI, Strings.toString(_tokenId)) ) : _placeholderURI; } } // File: https://github.com/RAT-TECHNOLOGIES/evm-contracts/blob/9820f1acbb53d4411ba120fb8af805bf519fb8a3/contracts/collections/ERC721/extensions/ERC721CollectionMetadataExtension.sol pragma solidity ^0.8.4; /** * @dev Extension to allow configuring contract-level collection metadata URI. */ abstract contract ERC721CollectionMetadataExtension is Ownable { string private _contractURI; constructor(string memory contractURI_) { _contractURI = contractURI_; } // ADMIN function setContractURI(string memory newValue) external onlyOwner { _contractURI = newValue; } // PUBLIC function contractURI() public view returns (string memory) { return _contractURI; } } // File: https://github.com/RAT-TECHNOLOGIES/evm-contracts/blob/9820f1acbb53d4411ba120fb8af805bf519fb8a3/contracts/collections/ERC721/presets/ERC721FullFeaturedCollection.sol pragma solidity ^0.8.4; contract ERC721FullFeaturedCollection is Ownable, ERC721, ERC721CollectionMetadataExtension, ERC721PrefixedMetadataExtension, ERC721AutoIdMinterExtension, ERC721OwnerMintExtension, ERC721PreSaleExtension, ERC721PublicSaleExtension, ERC721SimpleProceedsExtension, ERC721RoleBasedMintExtension, ERC721BulkifyExtension { constructor( string memory name, string memory symbol, string memory contractURI, string memory placeholderURI, uint256 maxSupply, uint256 preSalePrice, uint256 preSaleMaxMintPerWallet, uint256 publicSalePrice, uint256 publicSaleMaxMintPerTx ) ERC721(name, symbol) ERC721CollectionMetadataExtension(contractURI) ERC721PrefixedMetadataExtension(placeholderURI) ERC721AutoIdMinterExtension(maxSupply) ERC721PreSaleExtension(preSalePrice, preSaleMaxMintPerWallet) ERC721PublicSaleExtension(publicSalePrice, publicSaleMaxMintPerTx) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); } // PUBLIC /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view override(ERC721) returns (bool) { return super.isApprovedForAll(owner, operator); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721RoleBasedMintExtension) returns (bool) { return super.supportsInterface(interfaceId); } function tokenURI(uint256 _tokenId) public view virtual override(ERC721, ERC721PrefixedMetadataExtension) returns (string memory) { return ERC721PrefixedMetadataExtension.tokenURI(_tokenId); } function getInfo() external view returns ( uint256 _maxSupply, uint256 _totalSupply, uint256 _senderBalance, uint256 _preSalePrice, uint256 _preSaleMaxMintPerWallet, uint256 _preSaleAlreadyClaimed, bool _preSaleActive, uint256 _publicSalePrice, uint256 _publicSaleMaxMintPerTx, bool _publicSaleActive ) { uint256 balance = 0; if (msg.sender != address(0)) { balance = this.balanceOf(msg.sender); } return ( maxSupply, this.totalSupply(), balance, preSalePrice, preSaleMaxMintPerWallet, preSaleAllowlistClaimed[msg.sender], preSaleStatus, publicSalePrice, publicSaleMaxMintPerTx, publicSaleStatus ); } } // File: MyCollection.sol pragma solidity ^0.8.4; contract MyCollection is ERC721FullFeaturedCollection { constructor() ERC721FullFeaturedCollection( // Collection Name "The Gift Shop", // Collection Symbol "RATS", // Collection Metadata URL "ipfs/QmWei5kXGX9okYqupFfpbjhBmV1xyhTN7oH4VZJvmEonmA", // Pre-reveal Metadata URL "ipfs/QmWei5kXGX9okYqupFfpbjhBmV1xyhTN7oH4VZJvmEonmA", // Maximum Supply uint256(100000), // Pre Sale Price (in wei unit) uint256(10000000000000000), // Pre Sale max mint per wallet uint256(500), // Public Sale Price (in wei unit) uint256(10000000000000000), // Public Sale max mint per transaction uint256(500) ) {} }
Useful for when user wants to return tokens to get a refund, or when they want to transfer lots of tokens by paying gas fee only once./
function _beforeTokenTransfer( address from, address to, uint256 tokenId function _afterTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.4; ) public virtual { for (uint256 i = 0; i < tokenIds.length; i++) { require(_isApprovedOrOwner(_msgSender(), tokenIds[i]), "NOT_OWNER"); _transfer(from, to, tokenIds[i]); } }
1,119,027
./full_match/7700/0x468D623e538c4411109cf03d2C9047BF9AdD2299/sources/contracts/cedar/drop/CedarERC1155DropLogic.sol
Checks a request to claim NFTs against the active claim condition's criteria.
function verifyClaim( DropERC1155DataTypes.ClaimData storage claimData, uint256 _conditionId, address _claimer, uint256 _tokenId, uint256 _quantity, address _currency, uint256 _pricePerToken, bool verifyMaxQuantityPerTransaction ) public view { IDropClaimConditionV0.ClaimCondition memory currentClaimPhase = claimData.claimCondition[_tokenId].phases[ _conditionId ]; if (!(_currency == currentClaimPhase.currency && _pricePerToken == currentClaimPhase.pricePerToken)) { revert InvalidPrice(); } if ( !(_quantity > 0 && (!verifyMaxQuantityPerTransaction || _quantity <= currentClaimPhase.quantityLimitPerTransaction)) ) { revert CrossedLimitQuantityPerTransaction(); } if (!(currentClaimPhase.supplyClaimed + _quantity <= currentClaimPhase.maxClaimableSupply)) { revert CrossedLimitMaxClaimableSupply(); } if (_isOutOfLimits(claimData.maxTotalSupply[_tokenId], claimData.totalSupply[_tokenId] + _quantity)) { revert CrossedLimitMaxTotalSupply(); } if ( _isOutOfLimits( claimData.maxWalletClaimCount[_tokenId], claimData.walletClaimCount[_tokenId][_claimer] + _quantity ) ) { revert CrossedLimitMaxWalletClaimCount(); } (uint256 lastClaimTimestamp, uint256 nextValidClaimTimestamp) = getClaimTimestamp( claimData, _tokenId, _conditionId, _claimer ); if (!(lastClaimTimestamp == 0 || block.timestamp >= nextValidClaimTimestamp)) revert InvalidTime(); }
4,657,108
./full_match/1/0x113180ecac90987c7EB2757e608ecF2ab943554C/sources/project:/contracts/PurplecoinCrowdsale.sol
creates the token to be sold. override this method to have crowdsale of a specific ERC20Mintable token.
function createTokenContract() internal returns (ERC20Mintable) { return new Purplecoin(); }
4,830,611
./partial_match/56/0x836005b4382D8E952dd582DDf133F7C0f2b974c2/sources/MasterChef.sol
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.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 mulReward = multiplier.mul(mulPerBlock).mul(pool.allocPoint).div(totalAllocPoint); mul.mint(devaddr, mulReward.div(10)); mul.mint(address(this), mulReward); pool.accMulPerShare = pool.accMulPerShare.add(mulReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
11,150,883
./full_match/1/0x38D8FA043913e8Ef6466d01BEF4Af42Cafa3b235/sources/contracts/manager/DelegatedManager.sol
Initializes an added extension from PENDING to INITIALIZED state and adds to extension array. An address can only enter a PENDING state if it is an enabled extension added by the manager. Only callable by the extension itself, hence msg.sender is the subject of update./
function initializeExtension() external { require(extensionAllowlist[msg.sender] == ExtensionState.PENDING, "Extension must be pending"); extensionAllowlist[msg.sender] = ExtensionState.INITIALIZED; extensions.push(msg.sender); emit ExtensionInitialized(msg.sender); }
3,150,743
./full_match/1/0x998d69C79E2b97d398A29E855d9Ef2e301535e5e/sources/contracts/LazyVesting.sol
Returns a hash of the `contribution`, prepared using EIP712 typed data hashing rules./
function _hash(uint256 id, address contributor, uint256 amount, uint256 start) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( CONTRIBUTION_TYPEHASH, id, contributor, amount, start ))); }
9,606,024
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; 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) { if(_b > _a)throw; return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; if(c < _a)throw; return c; } } contract btoken is SafeMath{ string public name; string public icon; uint8 public decimals; uint256 totalSupply; address owner; //map any address to a balance mapping (bytes32 => uint256) public balances; /* * events */ event Transfer(bytes32 from, bytes32 to, uint value); event newMint(uint value); // only operate if the command comes from bridigette modifier onlyOwner(){ require(msg.sender == owner); _; } /* * 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 btoken(string _name, string _icon, uint8 _decimals, uint256 _initialSupply) public { balances[sha256("@DontPanicBurns#7712")] = _initialSupply; totalSupply = _initialSupply; name = _name; icon = _icon; decimals = _decimals; owner = msg.sender; } /* * 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 mint(uint value) public onlyOwner returns (bool success){ totalSupply = add(totalSupply, value); balances[sha256("DontPanicBurns#7712")] = add(balances[sha256("DontPanicBurns#7712")], value); newMint(value); 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 burns(uint _value, bytes _data) public returns (bool success){ if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = sub(balanceOf(msg.sender), _value); totalSupply = sub(totalSupply, _value); emit burnNotice(msg.sender, _value, _data); 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 returns (bool success) { return transferToAddress(_from, _to, _value); } /* function that is called when transaction target is an address * * @dev internal function */ function transferToAddress(bytes32 _from, bytes32 _to, uint _value) private returns (bool success) { if (balanceOf(_from) < _value) throw; balances[_from] = sub(balanceOf(_from), _value); balances[_to] = add(balanceOf(_to), _value); Transfer(_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]; } }
Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend)./
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { if(_b > _a)throw; return _a - _b; }
5,451,615
pragma solidity 0.5.17; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "../interfaces/Comptroller.sol"; import "../interfaces/PriceOracle.sol"; import "../interfaces/CERC20.sol"; import "../interfaces/CEther.sol"; import "../Utils.sol"; contract CompoundOrder is Utils(address(0), address(0), address(0)), Ownable { // Constants uint256 internal constant NEGLIGIBLE_DEBT = 100; // we don't care about debts below 10^-4 USDC (0.1 cent) uint256 internal constant MAX_REPAY_STEPS = 3; // Max number of times we attempt to repay remaining debt uint256 internal constant DEFAULT_LIQUIDITY_SLIPPAGE = 10 ** 12; // 1e-6 slippage for redeeming liquidity when selling order uint256 internal constant FALLBACK_LIQUIDITY_SLIPPAGE = 10 ** 15; // 0.1% slippage for redeeming liquidity when selling order uint256 internal constant MAX_LIQUIDITY_SLIPPAGE = 10 ** 17; // 10% max slippage for redeeming liquidity when selling order // Contract instances Comptroller public COMPTROLLER; // The Compound comptroller PriceOracle public ORACLE; // The Compound price oracle CERC20 public CUSDC; // The Compound USDC market token address public CETH_ADDR; // Instance variables uint256 public stake; uint256 public collateralAmountInUSDC; uint256 public loanAmountInUSDC; uint256 public cycleNumber; uint256 public buyTime; // Timestamp for order execution uint256 public outputAmount; // Records the total output USDC after order is sold address public compoundTokenAddr; bool public isSold; bool public orderType; // True for shorting, false for longing bool internal initialized; constructor() public {} function init( address _compoundTokenAddr, uint256 _cycleNumber, uint256 _stake, uint256 _collateralAmountInUSDC, uint256 _loanAmountInUSDC, bool _orderType, address _usdcAddr, address payable _kyberAddr, address _comptrollerAddr, address _priceOracleAddr, address _cUSDCAddr, address _cETHAddr ) public { require(!initialized); initialized = true; // Initialize details of order require(_compoundTokenAddr != _cUSDCAddr); require(_stake > 0 && _collateralAmountInUSDC > 0 && _loanAmountInUSDC > 0); // Validate inputs stake = _stake; collateralAmountInUSDC = _collateralAmountInUSDC; loanAmountInUSDC = _loanAmountInUSDC; cycleNumber = _cycleNumber; compoundTokenAddr = _compoundTokenAddr; orderType = _orderType; COMPTROLLER = Comptroller(_comptrollerAddr); ORACLE = PriceOracle(_priceOracleAddr); CUSDC = CERC20(_cUSDCAddr); CETH_ADDR = _cETHAddr; USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; usdc = ERC20Detailed(_usdcAddr); kyber = KyberNetwork(_kyberAddr); // transfer ownership to msg.sender _transferOwnership(msg.sender); } /** * @notice Executes the Compound order * @param _minPrice the minimum token price * @param _maxPrice the maximum token price */ function executeOrder(uint256 _minPrice, uint256 _maxPrice) public; /** * @notice Sells the Compound order and returns assets to PeakDeFiFund * @param _minPrice the minimum token price * @param _maxPrice the maximum token price */ function sellOrder(uint256 _minPrice, uint256 _maxPrice) public returns (uint256 _inputAmount, uint256 _outputAmount); /** * @notice Repays the loans taken out to prevent the collateral ratio from dropping below threshold * @param _repayAmountInUSDC the amount to repay, in USDC */ function repayLoan(uint256 _repayAmountInUSDC) public; /** * @notice Emergency method, which allow to transfer selected tokens to the fund address * @param _tokenAddr address of withdrawn token * @param _receiver address who should receive tokens */ function emergencyExitTokens(address _tokenAddr, address _receiver) public onlyOwner { ERC20Detailed token = ERC20Detailed(_tokenAddr); token.safeTransfer(_receiver, token.balanceOf(address(this))); } function getMarketCollateralFactor() public view returns (uint256); function getCurrentCollateralInUSDC() public returns (uint256 _amount); function getCurrentBorrowInUSDC() public returns (uint256 _amount); function getCurrentCashInUSDC() public view returns (uint256 _amount); /** * @notice Calculates the current profit in USDC * @return the profit amount */ function getCurrentProfitInUSDC() public returns (bool _isNegative, uint256 _amount) { uint256 l; uint256 r; if (isSold) { l = outputAmount; r = collateralAmountInUSDC; } else { uint256 cash = getCurrentCashInUSDC(); uint256 supply = getCurrentCollateralInUSDC(); uint256 borrow = getCurrentBorrowInUSDC(); if (cash >= borrow) { l = supply.add(cash); r = borrow.add(collateralAmountInUSDC); } else { l = supply; r = borrow.sub(cash).mul(PRECISION).div(getMarketCollateralFactor()).add(collateralAmountInUSDC); } } if (l >= r) { return (false, l.sub(r)); } else { return (true, r.sub(l)); } } /** * @notice Calculates the current collateral ratio on Compound, using 18 decimals * @return the collateral ratio */ function getCurrentCollateralRatioInUSDC() public returns (uint256 _amount) { uint256 supply = getCurrentCollateralInUSDC(); uint256 borrow = getCurrentBorrowInUSDC(); if (borrow == 0) { return uint256(-1); } return supply.mul(PRECISION).div(borrow); } /** * @notice Calculates the current liquidity (supply - collateral) on the Compound platform * @return the liquidity */ function getCurrentLiquidityInUSDC() public returns (bool _isNegative, uint256 _amount) { uint256 supply = getCurrentCollateralInUSDC(); uint256 borrow = getCurrentBorrowInUSDC().mul(PRECISION).div(getMarketCollateralFactor()); if (supply >= borrow) { return (false, supply.sub(borrow)); } else { return (true, borrow.sub(supply)); } } function __sellUSDCForToken(uint256 _usdcAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) { ERC20Detailed t = __underlyingToken(compoundTokenAddr); (,, _actualTokenAmount, _actualUSDCAmount) = __kyberTrade(usdc, _usdcAmount, t); // Sell USDC for tokens on Kyber require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values } function __sellTokenForUSDC(uint256 _tokenAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) { ERC20Detailed t = __underlyingToken(compoundTokenAddr); (,, _actualUSDCAmount, _actualTokenAmount) = __kyberTrade(t, _tokenAmount, usdc); // Sell tokens for USDC on Kyber require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values } // Convert a USDC amount to the amount of a given token that's of equal value function __usdcToToken(address _cToken, uint256 _usdcAmount) internal view returns (uint256) { ERC20Detailed t = __underlyingToken(_cToken); return _usdcAmount.mul(PRECISION).div(10 ** getDecimals(usdc)).mul(10 ** getDecimals(t)).div(ORACLE.getUnderlyingPrice(_cToken).mul(10 ** getDecimals(t)).div(PRECISION)); } // Convert a compound token amount to the amount of USDC that's of equal value function __tokenToUSDC(address _cToken, uint256 _tokenAmount) internal view returns (uint256) { return _tokenAmount.mul(ORACLE.getUnderlyingPrice(_cToken)).div(PRECISION).mul(10 ** getDecimals(usdc)).div(PRECISION); } function __underlyingToken(address _cToken) internal view returns (ERC20Detailed) { if (_cToken == CETH_ADDR) { // ETH return ETH_TOKEN_ADDRESS; } CERC20 ct = CERC20(_cToken); address underlyingToken = ct.underlying(); ERC20Detailed t = ERC20Detailed(underlyingToken); return t; } function() external payable {} } pragma solidity ^0.5.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity 0.5.17; // Compound finance comptroller interface Comptroller { function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function markets(address cToken) external view returns (bool isListed, uint256 collateralFactorMantissa); } pragma solidity 0.5.17; // Compound finance's price oracle interface PriceOracle { // returns the price of the underlying token in USD, scaled by 10**(36 - underlyingPrecision) function getUnderlyingPrice(address cToken) external view returns (uint); } pragma solidity 0.5.17; // Compound finance ERC20 market interface interface CERC20 { function mint(uint mintAmount) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function exchangeRateCurrent() external returns (uint); function balanceOf(address account) external view returns (uint); function decimals() external view returns (uint); function underlying() external view returns (address); } pragma solidity 0.5.17; // Compound finance Ether market interface interface CEther { function mint() external payable; function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow() external payable; function borrowBalanceCurrent(address account) external returns (uint); function exchangeRateCurrent() external returns (uint); function balanceOf(address account) external view returns (uint); function decimals() external view returns (uint); } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/KyberNetwork.sol"; import "./interfaces/OneInchExchange.sol"; /** * @title The smart contract for useful utility functions and constants. * @author Zefram Lou (Zebang Liu) */ contract Utils { using SafeMath for uint256; using SafeERC20 for ERC20Detailed; /** * @notice Checks if `_token` is a valid token. * @param _token the token's address */ modifier isValidToken(address _token) { require(_token != address(0)); if (_token != address(ETH_TOKEN_ADDRESS)) { require(isContract(_token)); } _; } address public USDC_ADDR; address payable public KYBER_ADDR; address payable public ONEINCH_ADDR; bytes public constant PERM_HINT = "PERM"; // The address Kyber Network uses to represent Ether ERC20Detailed internal constant ETH_TOKEN_ADDRESS = ERC20Detailed(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); ERC20Detailed internal usdc; KyberNetwork internal kyber; uint256 constant internal PRECISION = (10**18); uint256 constant internal MAX_QTY = (10**28); // 10B tokens uint256 constant internal ETH_DECIMALS = 18; uint256 constant internal MAX_DECIMALS = 18; constructor( address _usdcAddr, address payable _kyberAddr, address payable _oneInchAddr ) public { USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; ONEINCH_ADDR = _oneInchAddr; usdc = ERC20Detailed(_usdcAddr); kyber = KyberNetwork(_kyberAddr); } /** * @notice Get the number of decimals of a token * @param _token the token to be queried * @return number of decimals */ function getDecimals(ERC20Detailed _token) internal view returns(uint256) { if (address(_token) == address(ETH_TOKEN_ADDRESS)) { return uint256(ETH_DECIMALS); } return uint256(_token.decimals()); } /** * @notice Get the token balance of an account * @param _token the token to be queried * @param _addr the account whose balance will be returned * @return token balance of the account */ function getBalance(ERC20Detailed _token, address _addr) internal view returns(uint256) { if (address(_token) == address(ETH_TOKEN_ADDRESS)) { return uint256(_addr.balance); } return uint256(_token.balanceOf(_addr)); } /** * @notice Calculates the rate of a trade. The rate is the price of the source token in the dest token, in 18 decimals. * Note: the rate is on the token level, not the wei level, so for example if 1 Atoken = 10 Btoken, then the rate * from A to B is 10 * 10**18, regardless of how many decimals each token uses. * @param srcAmount amount of source token * @param destAmount amount of dest token * @param srcDecimals decimals used by source token * @param dstDecimals decimals used by dest token */ function calcRateFromQty(uint256 srcAmount, uint256 destAmount, uint256 srcDecimals, uint256 dstDecimals) internal pure returns(uint) { require(srcAmount <= MAX_QTY); require(destAmount <= MAX_QTY); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount); } } /** * @notice Wrapper function for doing token conversion on Kyber Network * @param _srcToken the token to convert from * @param _srcAmount the amount of tokens to be converted * @param _destToken the destination token * @return _destPriceInSrc the price of the dest token, in terms of source tokens * _srcPriceInDest the price of the source token, in terms of dest tokens * _actualDestAmount actual amount of dest token traded * _actualSrcAmount actual amount of src token traded */ function __kyberTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken) internal returns( uint256 _destPriceInSrc, uint256 _srcPriceInDest, uint256 _actualDestAmount, uint256 _actualSrcAmount ) { require(_srcToken != _destToken); uint256 beforeSrcBalance = getBalance(_srcToken, address(this)); uint256 msgValue; if (_srcToken != ETH_TOKEN_ADDRESS) { msgValue = 0; _srcToken.safeApprove(KYBER_ADDR, 0); _srcToken.safeApprove(KYBER_ADDR, _srcAmount); } else { msgValue = _srcAmount; } _actualDestAmount = kyber.tradeWithHint.value(msgValue)( _srcToken, _srcAmount, _destToken, toPayableAddr(address(this)), MAX_QTY, 1, address(0), PERM_HINT ); _actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this))); require(_actualDestAmount > 0 && _actualSrcAmount > 0); _destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken)); _srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken)); } /** * @notice Wrapper function for doing token conversion on 1inch * @param _srcToken the token to convert from * @param _srcAmount the amount of tokens to be converted * @param _destToken the destination token * @return _destPriceInSrc the price of the dest token, in terms of source tokens * _srcPriceInDest the price of the source token, in terms of dest tokens * _actualDestAmount actual amount of dest token traded * _actualSrcAmount actual amount of src token traded */ function __oneInchTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken, bytes memory _calldata) internal returns( uint256 _destPriceInSrc, uint256 _srcPriceInDest, uint256 _actualDestAmount, uint256 _actualSrcAmount ) { require(_srcToken != _destToken); uint256 beforeSrcBalance = getBalance(_srcToken, address(this)); uint256 beforeDestBalance = getBalance(_destToken, address(this)); // Note: _actualSrcAmount is being used as msgValue here, because otherwise we'd run into the stack too deep error if (_srcToken != ETH_TOKEN_ADDRESS) { _actualSrcAmount = 0; OneInchExchange dex = OneInchExchange(ONEINCH_ADDR); address approvalHandler = dex.spender(); _srcToken.safeApprove(approvalHandler, 0); _srcToken.safeApprove(approvalHandler, _srcAmount); } else { _actualSrcAmount = _srcAmount; } // trade through 1inch proxy (bool success,) = ONEINCH_ADDR.call.value(_actualSrcAmount)(_calldata); require(success); // calculate trade amounts and price _actualDestAmount = getBalance(_destToken, address(this)).sub(beforeDestBalance); _actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this))); require(_actualDestAmount > 0 && _actualSrcAmount > 0); _destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken)); _srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken)); } /** * @notice Checks if an Ethereum account is a smart contract * @param _addr the account to be checked * @return True if the account is a smart contract, false otherwise */ function isContract(address _addr) internal view returns(bool) { uint256 size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size>0; } function toPayableAddr(address _addr) internal pure returns (address payable) { return address(uint160(_addr)); } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } pragma solidity ^0.5.0; /** * @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); } pragma solidity ^0.5.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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; /** * @title The interface for the Kyber Network smart contract * @author Zefram Lou (Zebang Liu) */ interface KyberNetwork { function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function tradeWithHint( ERC20Detailed src, uint srcAmount, ERC20Detailed dest, address payable destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes calldata hint) external payable returns(uint); } pragma solidity 0.5.17; interface OneInchExchange { function spender() external view returns (address); } pragma solidity 0.5.17; import "./LongCERC20Order.sol"; import "./LongCEtherOrder.sol"; import "./ShortCERC20Order.sol"; import "./ShortCEtherOrder.sol"; import "../lib/CloneFactory.sol"; contract CompoundOrderFactory is CloneFactory { address public SHORT_CERC20_LOGIC_CONTRACT; address public SHORT_CEther_LOGIC_CONTRACT; address public LONG_CERC20_LOGIC_CONTRACT; address public LONG_CEther_LOGIC_CONTRACT; address public USDC_ADDR; address payable public KYBER_ADDR; address public COMPTROLLER_ADDR; address public ORACLE_ADDR; address public CUSDC_ADDR; address public CETH_ADDR; constructor( address _shortCERC20LogicContract, address _shortCEtherLogicContract, address _longCERC20LogicContract, address _longCEtherLogicContract, address _usdcAddr, address payable _kyberAddr, address _comptrollerAddr, address _priceOracleAddr, address _cUSDCAddr, address _cETHAddr ) public { SHORT_CERC20_LOGIC_CONTRACT = _shortCERC20LogicContract; SHORT_CEther_LOGIC_CONTRACT = _shortCEtherLogicContract; LONG_CERC20_LOGIC_CONTRACT = _longCERC20LogicContract; LONG_CEther_LOGIC_CONTRACT = _longCEtherLogicContract; USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; COMPTROLLER_ADDR = _comptrollerAddr; ORACLE_ADDR = _priceOracleAddr; CUSDC_ADDR = _cUSDCAddr; CETH_ADDR = _cETHAddr; } function createOrder( address _compoundTokenAddr, uint256 _cycleNumber, uint256 _stake, uint256 _collateralAmountInUSDC, uint256 _loanAmountInUSDC, bool _orderType ) external returns (CompoundOrder) { require(_compoundTokenAddr != address(0)); CompoundOrder order; address payable clone; if (_compoundTokenAddr != CETH_ADDR) { if (_orderType) { // Short CERC20 Order clone = toPayableAddr(createClone(SHORT_CERC20_LOGIC_CONTRACT)); } else { // Long CERC20 Order clone = toPayableAddr(createClone(LONG_CERC20_LOGIC_CONTRACT)); } } else { if (_orderType) { // Short CEther Order clone = toPayableAddr(createClone(SHORT_CEther_LOGIC_CONTRACT)); } else { // Long CEther Order clone = toPayableAddr(createClone(LONG_CEther_LOGIC_CONTRACT)); } } order = CompoundOrder(clone); order.init(_compoundTokenAddr, _cycleNumber, _stake, _collateralAmountInUSDC, _loanAmountInUSDC, _orderType, USDC_ADDR, KYBER_ADDR, COMPTROLLER_ADDR, ORACLE_ADDR, CUSDC_ADDR, CETH_ADDR); order.transferOwnership(msg.sender); return order; } function getMarketCollateralFactor(address _compoundTokenAddr) external view returns (uint256) { Comptroller troll = Comptroller(COMPTROLLER_ADDR); (, uint256 factor) = troll.markets(_compoundTokenAddr); return factor; } function tokenIsListed(address _compoundTokenAddr) external view returns (bool) { Comptroller troll = Comptroller(COMPTROLLER_ADDR); (bool isListed,) = troll.markets(_compoundTokenAddr); return isListed; } function toPayableAddr(address _addr) internal pure returns (address payable) { return address(uint160(_addr)); } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract LongCERC20Order is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Convert received USDC to longing token (,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC); // Enter Compound markets CERC20 market = CERC20(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in USDC ERC20Detailed token = __underlyingToken(compoundTokenAddr); token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound token.safeApprove(compoundTokenAddr, actualTokenAmount); // Approve token transfer to Compound require(market.mint(actualTokenAmount) == 0); // Transfer tokens into Compound as supply token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert borrowed USDC to longing token __sellUSDCForToken(loanAmountInUSDC); // Repay leftover USDC to avoid complications if (usdc.balanceOf(address(this)) > 0) { uint256 repayAmount = usdc.balanceOf(address(this)); usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), repayAmount); require(CUSDC.repayBorrow(repayAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted CERC20 market = CERC20(compoundTokenAddr); ERC20Detailed token = __underlyingToken(compoundTokenAddr); for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { liquidity = __usdcToToken(compoundTokenAddr, liquidity); uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Sell all longing token to USDC __sellTokenForUSDC(token.balanceOf(address(this))); // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); uint256 leftoverTokens = token.balanceOf(address(this)); if (leftoverTokens > 0) { token.safeTransfer(owner(), leftoverTokens); // Send back potential leftover tokens } } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert longing token to USDC uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC); (uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken); // Check if amount is greater than borrow balance uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this)); if (actualUSDCAmount > currentDebt) { actualUSDCAmount = currentDebt; } // Repay loan to Compound usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), actualUSDCAmount); require(CUSDC.repayBorrow(actualUSDCAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { CERC20 market = CERC20(compoundTokenAddr); uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION)); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { uint256 borrow = CUSDC.borrowBalanceCurrent(address(this)); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { ERC20Detailed token = __underlyingToken(compoundTokenAddr); uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this))); return cash; } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract LongCEtherOrder is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Convert received USDC to longing token (,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC); // Enter Compound markets CEther market = CEther(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in USDC market.mint.value(actualTokenAmount)(); // Transfer tokens into Compound as supply require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert borrowed USDC to longing token __sellUSDCForToken(loanAmountInUSDC); // Repay leftover USDC to avoid complications if (usdc.balanceOf(address(this)) > 0) { uint256 repayAmount = usdc.balanceOf(address(this)); usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), repayAmount); require(CUSDC.repayBorrow(repayAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted CEther market = CEther(compoundTokenAddr); for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { liquidity = __usdcToToken(compoundTokenAddr, liquidity); uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Sell all longing token to USDC __sellTokenForUSDC(address(this).balance); // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); toPayableAddr(owner()).transfer(address(this).balance); // Send back potential leftover tokens } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert longing token to USDC uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC); (uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken); // Check if amount is greater than borrow balance uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this)); if (actualUSDCAmount > currentDebt) { actualUSDCAmount = currentDebt; } // Repay loan to Compound usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), actualUSDCAmount); require(CUSDC.repayBorrow(actualUSDCAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { CEther market = CEther(compoundTokenAddr); uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION)); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { uint256 borrow = CUSDC.borrowBalanceCurrent(address(this)); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { ERC20Detailed token = __underlyingToken(compoundTokenAddr); uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this))); return cash; } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract ShortCERC20Order is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Enter Compound markets CERC20 market = CERC20(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in tokenAddr uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC); usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply usdc.safeApprove(address(CUSDC), 0); require(market.borrow(loanAmountInToken) == 0);// Take out loan (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert loaned tokens to USDC (uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken); loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received // Repay leftover tokens to avoid complications ERC20Detailed token = __underlyingToken(compoundTokenAddr); if (token.balanceOf(address(this)) > 0) { uint256 repayAmount = token.balanceOf(address(this)); token.safeApprove(compoundTokenAddr, 0); token.safeApprove(compoundTokenAddr, repayAmount); require(market.repayBorrow(repayAmount) == 0); token.safeApprove(compoundTokenAddr, 0); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert USDC to shorting token (,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC); // Check if amount is greater than borrow balance CERC20 market = CERC20(compoundTokenAddr); uint256 currentDebt = market.borrowBalanceCurrent(address(this)); if (actualTokenAmount > currentDebt) { actualTokenAmount = currentDebt; } // Repay loan to Compound ERC20Detailed token = __underlyingToken(compoundTokenAddr); token.safeApprove(compoundTokenAddr, 0); token.safeApprove(compoundTokenAddr, actualTokenAmount); require(market.repayBorrow(actualTokenAmount) == 0); token.safeApprove(compoundTokenAddr, 0); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(CUSDC)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { CERC20 market = CERC20(compoundTokenAddr); uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this))); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { uint256 cash = getBalance(usdc, address(this)); return cash; } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract ShortCEtherOrder is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Enter Compound markets CEther market = CEther(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in tokenAddr uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC); usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply usdc.safeApprove(address(CUSDC), 0); require(market.borrow(loanAmountInToken) == 0);// Take out loan (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert loaned tokens to USDC (uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken); loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received // Repay leftover tokens to avoid complications if (address(this).balance > 0) { uint256 repayAmount = address(this).balance; market.repayBorrow.value(repayAmount)(); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted for (uint256 i = 0; i < MAX_REPAY_STEPS; i = i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert USDC to shorting token (,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC); // Check if amount is greater than borrow balance CEther market = CEther(compoundTokenAddr); uint256 currentDebt = market.borrowBalanceCurrent(address(this)); if (actualTokenAmount > currentDebt) { actualTokenAmount = currentDebt; } // Repay loan to Compound market.repayBorrow.value(actualTokenAmount)(); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(CUSDC)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { CEther market = CEther(compoundTokenAddr); uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this))); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { uint256 cash = getBalance(usdc, address(this)); return cash; } } pragma solidity 0.5.17; /* 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. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly contract CloneFactory { function createClone(address target) internal returns (address result) { 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) } } function isClone(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000) mstore(add(clone, 0xa), targetBytes) mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and( eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))) ) } } } pragma solidity 0.5.17; interface IMiniMeToken { function balanceOf(address _owner) external view returns (uint256 balance); function totalSupply() external view returns(uint); function generateTokens(address _owner, uint _amount) external returns (bool); function destroyTokens(address _owner, uint _amount) external returns (bool); function totalSupplyAt(uint _blockNumber) external view returns(uint); function balanceOfAt(address _holder, uint _blockNumber) external view returns (uint); function transferOwnership(address newOwner) external; } pragma solidity ^0.5.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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; function __initReentrancyGuard() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } pragma solidity 0.5.17; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.17; // interface for contract_v6/UniswapOracle.sol interface IUniswapOracle { function update() external returns (bool success); function consult(address token, uint256 amountIn) external view returns (uint256 amountOut); } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Capped.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; contract PeakToken is ERC20, ERC20Detailed, ERC20Capped, ERC20Burnable { constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap ) ERC20Detailed(name, symbol, decimals) ERC20Capped(cap) public {} } pragma solidity ^0.5.0; import "../../GSN/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 {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")); } } pragma solidity ^0.5.0; import "./ERC20Mintable.sol"; /** * @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20Mintable-mint}. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } pragma solidity ^0.5.0; import "./ERC20.sol"; import "../../access/roles/MinterRole.sol"; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } pragma solidity ^0.5.0; import "../../GSN/Context.sol"; import "../Roles.sol"; contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } pragma solidity ^0.5.0; import "../../GSN/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). */ contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/roles/SignerRole.sol"; import "../staking/PeakStaking.sol"; import "../PeakToken.sol"; import "../IUniswapOracle.sol"; contract PeakReward is SignerRole { using SafeMath for uint256; using SafeERC20 for IERC20; event Register(address user, address referrer); event RankChange(address user, uint256 oldRank, uint256 newRank); event PayCommission( address referrer, address recipient, address token, uint256 amount, uint8 level ); event ChangedCareerValue(address user, uint256 changeAmount, bool positive); event ReceiveRankReward(address user, uint256 peakReward); modifier regUser(address user) { if (!isUser[user]) { isUser[user] = true; emit Register(user, address(0)); } _; } uint256 public constant PEAK_MINT_CAP = 5 * 10**15; // 50 million PEAK uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20% uint256 internal constant PEAK_PRECISION = 10**8; uint256 internal constant USDC_PRECISION = 10**6; uint8 internal constant COMMISSION_LEVELS = 8; mapping(address => address) public referrerOf; mapping(address => bool) public isUser; mapping(address => uint256) public careerValue; // AKA DSV mapping(address => uint256) public rankOf; mapping(uint256 => mapping(uint256 => uint256)) public rankReward; // (beforeRank, afterRank) => rewardInPeak mapping(address => mapping(uint256 => uint256)) public downlineRanks; // (referrer, rank) => numReferredUsersWithRank uint256[] public commissionPercentages; uint256[] public commissionStakeRequirements; uint256 public mintedPeakTokens; address public marketPeakWallet; PeakStaking public peakStaking; PeakToken public peakToken; address public stablecoin; IUniswapOracle public oracle; constructor( address _marketPeakWallet, address _peakStaking, address _peakToken, address _stablecoin, address _oracle ) public { // initialize commission percentages for each level commissionPercentages.push(10 * (10**16)); // 10% commissionPercentages.push(4 * (10**16)); // 4% commissionPercentages.push(2 * (10**16)); // 2% commissionPercentages.push(1 * (10**16)); // 1% commissionPercentages.push(1 * (10**16)); // 1% commissionPercentages.push(1 * (10**16)); // 1% commissionPercentages.push(5 * (10**15)); // 0.5% commissionPercentages.push(5 * (10**15)); // 0.5% // initialize commission stake requirements for each level commissionStakeRequirements.push(0); commissionStakeRequirements.push(PEAK_PRECISION.mul(2000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(4000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(6000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(7000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(8000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(9000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(10000)); // initialize rank rewards for (uint256 i = 0; i < 8; i = i.add(1)) { uint256 rewardInUSDC = 0; for (uint256 j = i.add(1); j <= 8; j = j.add(1)) { if (j == 1) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(100)); } else if (j == 2) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(300)); } else if (j == 3) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(600)); } else if (j == 4) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(1200)); } else if (j == 5) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(2400)); } else if (j == 6) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(7500)); } else if (j == 7) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(15000)); } else { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(50000)); } rankReward[i][j] = rewardInUSDC; } } marketPeakWallet = _marketPeakWallet; peakStaking = PeakStaking(_peakStaking); peakToken = PeakToken(_peakToken); stablecoin = _stablecoin; oracle = IUniswapOracle(_oracle); } /** @notice Registers a group of referrals relationship. @param users The array of users @param referrers The group of referrers of `users` */ function multiRefer(address[] calldata users, address[] calldata referrers) external onlySigner { require(users.length == referrers.length, "PeakReward: arrays length are not equal"); for (uint256 i = 0; i < users.length; i++) { refer(users[i], referrers[i]); } } /** @notice Registers a referral relationship @param user The user who is being referred @param referrer The referrer of `user` */ function refer(address user, address referrer) public onlySigner { require(!isUser[user], "PeakReward: referred is already a user"); require(user != referrer, "PeakReward: can't refer self"); require( user != address(0) && referrer != address(0), "PeakReward: 0 address" ); isUser[user] = true; isUser[referrer] = true; referrerOf[user] = referrer; downlineRanks[referrer][0] = downlineRanks[referrer][0].add(1); emit Register(user, referrer); } function canRefer(address user, address referrer) public view returns (bool) { return !isUser[user] && user != referrer && user != address(0) && referrer != address(0); } /** @notice Distributes commissions to a referrer and their referrers @param referrer The referrer who will receive commission @param commissionToken The ERC20 token that the commission is paid in @param rawCommission The raw commission that will be distributed amongst referrers @param returnLeftovers If true, leftover commission is returned to the sender. If false, leftovers will be paid to MarketPeak. */ function payCommission( address referrer, address commissionToken, uint256 rawCommission, bool returnLeftovers ) public regUser(referrer) onlySigner returns (uint256 leftoverAmount) { // transfer the raw commission from `msg.sender` IERC20 token = IERC20(commissionToken); token.safeTransferFrom(msg.sender, address(this), rawCommission); // payout commissions to referrers of different levels address ptr = referrer; uint256 commissionLeft = rawCommission; uint8 i = 0; while (ptr != address(0) && i < COMMISSION_LEVELS) { if (_peakStakeOf(ptr) >= commissionStakeRequirements[i]) { // referrer has enough stake, give commission uint256 com = rawCommission.mul(commissionPercentages[i]).div( COMMISSION_RATE ); if (com > commissionLeft) { com = commissionLeft; } token.safeTransfer(ptr, com); commissionLeft = commissionLeft.sub(com); if (commissionToken == address(peakToken)) { incrementCareerValueInPeak(ptr, com); } else if (commissionToken == stablecoin) { incrementCareerValueInUsdc(ptr, com); } emit PayCommission(referrer, ptr, commissionToken, com, i); } ptr = referrerOf[ptr]; i += 1; } // handle leftovers if (returnLeftovers) { // return leftovers to `msg.sender` token.safeTransfer(msg.sender, commissionLeft); return commissionLeft; } else { // give leftovers to MarketPeak wallet token.safeTransfer(marketPeakWallet, commissionLeft); return 0; } } /** @notice Increments a user's career value @param user The user @param incCV The CV increase amount, in Usdc */ function incrementCareerValueInUsdc(address user, uint256 incCV) public regUser(user) onlySigner { careerValue[user] = careerValue[user].add(incCV); emit ChangedCareerValue(user, incCV, true); } /** @notice Increments a user's career value @param user The user @param incCVInPeak The CV increase amount, in PEAK tokens */ function incrementCareerValueInPeak(address user, uint256 incCVInPeak) public regUser(user) onlySigner { uint256 peakPriceInUsdc = _getPeakPriceInUsdc(); uint256 incCVInUsdc = incCVInPeak.mul(peakPriceInUsdc).div( PEAK_PRECISION ); careerValue[user] = careerValue[user].add(incCVInUsdc); emit ChangedCareerValue(user, incCVInUsdc, true); } /** @notice Returns a user's rank in the PeakDeFi system based only on career value @param user The user whose rank will be queried */ function cvRankOf(address user) public view returns (uint256) { uint256 cv = careerValue[user]; if (cv < USDC_PRECISION.mul(100)) { return 0; } else if (cv < USDC_PRECISION.mul(250)) { return 1; } else if (cv < USDC_PRECISION.mul(750)) { return 2; } else if (cv < USDC_PRECISION.mul(1500)) { return 3; } else if (cv < USDC_PRECISION.mul(3000)) { return 4; } else if (cv < USDC_PRECISION.mul(10000)) { return 5; } else if (cv < USDC_PRECISION.mul(50000)) { return 6; } else if (cv < USDC_PRECISION.mul(150000)) { return 7; } else { return 8; } } function rankUp(address user) external { // verify rank up conditions uint256 currentRank = rankOf[user]; uint256 cvRank = cvRankOf(user); require(cvRank > currentRank, "PeakReward: career value is not enough!"); require(downlineRanks[user][currentRank] >= 2 || currentRank == 0, "PeakReward: downlines count and requirement not passed!"); // Target rank always should be +1 rank from current rank uint256 targetRank = currentRank + 1; // increase user rank rankOf[user] = targetRank; emit RankChange(user, currentRank, targetRank); address referrer = referrerOf[user]; if (referrer != address(0)) { downlineRanks[referrer][targetRank] = downlineRanks[referrer][targetRank] .add(1); downlineRanks[referrer][currentRank] = downlineRanks[referrer][currentRank] .sub(1); } // give user rank reward uint256 rewardInPeak = rankReward[currentRank][targetRank] .mul(PEAK_PRECISION) .div(_getPeakPriceInUsdc()); if (mintedPeakTokens.add(rewardInPeak) <= PEAK_MINT_CAP) { // mint if under cap, do nothing if over cap mintedPeakTokens = mintedPeakTokens.add(rewardInPeak); peakToken.mint(user, rewardInPeak); emit ReceiveRankReward(user, rewardInPeak); } } function canRankUp(address user) external view returns (bool) { uint256 currentRank = rankOf[user]; uint256 cvRank = cvRankOf(user); return (cvRank > currentRank) && (downlineRanks[user][currentRank] >= 2 || currentRank == 0); } /** @notice Returns a user's current staked PEAK amount, scaled by `PEAK_PRECISION`. @param user The user whose stake will be queried */ function _peakStakeOf(address user) internal view returns (uint256) { return peakStaking.userStakeAmount(user); } /** @notice Returns the price of PEAK token in Usdc, scaled by `USDC_PRECISION`. */ function _getPeakPriceInUsdc() internal returns (uint256) { oracle.update(); uint256 priceInUSDC = oracle.consult(address(peakToken), PEAK_PRECISION); if (priceInUSDC == 0) { return USDC_PRECISION.mul(3).div(10); } return priceInUSDC; } } pragma solidity ^0.5.0; import "../../GSN/Context.sol"; import "../Roles.sol"; contract SignerRole is Context { using Roles for Roles.Role; event SignerAdded(address indexed account); event SignerRemoved(address indexed account); Roles.Role private _signers; constructor () internal { _addSigner(_msgSender()); } modifier onlySigner() { require(isSigner(_msgSender()), "SignerRole: caller does not have the Signer role"); _; } function isSigner(address account) public view returns (bool) { return _signers.has(account); } function addSigner(address account) public onlySigner { _addSigner(account); } function renounceSigner() public { _removeSigner(_msgSender()); } function _addSigner(address account) internal { _signers.add(account); emit SignerAdded(account); } function _removeSigner(address account) internal { _signers.remove(account); emit SignerRemoved(account); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../reward/PeakReward.sol"; import "../PeakToken.sol"; contract PeakStaking { using SafeMath for uint256; using SafeERC20 for PeakToken; event CreateStake( uint256 idx, address user, address referrer, uint256 stakeAmount, uint256 stakeTimeInDays, uint256 interestAmount ); event ReceiveStakeReward(uint256 idx, address user, uint256 rewardAmount); event WithdrawReward(uint256 idx, address user, uint256 rewardAmount); event WithdrawStake(uint256 idx, address user); uint256 internal constant PRECISION = 10**18; uint256 internal constant PEAK_PRECISION = 10**8; uint256 internal constant INTEREST_SLOPE = 2 * (10**8); // Interest rate factor drops to 0 at 5B mintedPeakTokens uint256 internal constant BIGGER_BONUS_DIVISOR = 10**15; // biggerBonus = stakeAmount / (10 million peak) uint256 internal constant MAX_BIGGER_BONUS = 10**17; // biggerBonus <= 10% uint256 internal constant DAILY_BASE_REWARD = 15 * (10**14); // dailyBaseReward = 0.0015 uint256 internal constant DAILY_GROWING_REWARD = 10**12; // dailyGrowingReward = 1e-6 uint256 internal constant MAX_STAKE_PERIOD = 1000; // Max staking time is 1000 days uint256 internal constant MIN_STAKE_PERIOD = 10; // Min staking time is 10 days uint256 internal constant DAY_IN_SECONDS = 86400; uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20% uint256 internal constant REFERRAL_STAKER_BONUS = 3 * (10**16); // 3% uint256 internal constant YEAR_IN_DAYS = 365; uint256 public constant PEAK_MINT_CAP = 7 * 10**16; // 700 million PEAK struct Stake { address staker; uint256 stakeAmount; uint256 interestAmount; uint256 withdrawnInterestAmount; uint256 stakeTimestamp; uint256 stakeTimeInDays; bool active; } Stake[] public stakeList; mapping(address => uint256) public userStakeAmount; uint256 public mintedPeakTokens; bool public initialized; PeakToken public peakToken; PeakReward public peakReward; constructor(address _peakToken) public { peakToken = PeakToken(_peakToken); } function init(address _peakReward) public { require(!initialized, "PeakStaking: Already initialized"); initialized = true; peakReward = PeakReward(_peakReward); } function stake( uint256 stakeAmount, uint256 stakeTimeInDays, address referrer ) public returns (uint256 stakeIdx) { require( stakeTimeInDays >= MIN_STAKE_PERIOD, "PeakStaking: stakeTimeInDays < MIN_STAKE_PERIOD" ); require( stakeTimeInDays <= MAX_STAKE_PERIOD, "PeakStaking: stakeTimeInDays > MAX_STAKE_PERIOD" ); // record stake uint256 interestAmount = getInterestAmount( stakeAmount, stakeTimeInDays ); stakeIdx = stakeList.length; stakeList.push( Stake({ staker: msg.sender, stakeAmount: stakeAmount, interestAmount: interestAmount, withdrawnInterestAmount: 0, stakeTimestamp: now, stakeTimeInDays: stakeTimeInDays, active: true }) ); mintedPeakTokens = mintedPeakTokens.add(interestAmount); userStakeAmount[msg.sender] = userStakeAmount[msg.sender].add( stakeAmount ); // transfer PEAK from msg.sender peakToken.safeTransferFrom(msg.sender, address(this), stakeAmount); // mint PEAK interest peakToken.mint(address(this), interestAmount); // handle referral if (peakReward.canRefer(msg.sender, referrer)) { peakReward.refer(msg.sender, referrer); } address actualReferrer = peakReward.referrerOf(msg.sender); if (actualReferrer != address(0)) { // pay referral bonus to referrer uint256 rawCommission = interestAmount.mul(COMMISSION_RATE).div( PRECISION ); peakToken.mint(address(this), rawCommission); peakToken.safeApprove(address(peakReward), rawCommission); uint256 leftoverAmount = peakReward.payCommission( actualReferrer, address(peakToken), rawCommission, true ); peakToken.burn(leftoverAmount); // pay referral bonus to staker uint256 referralStakerBonus = interestAmount .mul(REFERRAL_STAKER_BONUS) .div(PRECISION); peakToken.mint(msg.sender, referralStakerBonus); mintedPeakTokens = mintedPeakTokens.add( rawCommission.sub(leftoverAmount).add(referralStakerBonus) ); emit ReceiveStakeReward(stakeIdx, msg.sender, referralStakerBonus); } require(mintedPeakTokens <= PEAK_MINT_CAP, "PeakStaking: reached cap"); emit CreateStake( stakeIdx, msg.sender, actualReferrer, stakeAmount, stakeTimeInDays, interestAmount ); } function withdraw(uint256 stakeIdx) public { Stake storage stakeObj = stakeList[stakeIdx]; require( stakeObj.staker == msg.sender, "PeakStaking: Sender not staker" ); require(stakeObj.active, "PeakStaking: Not active"); // calculate amount that can be withdrawn uint256 stakeTimeInSeconds = stakeObj.stakeTimeInDays.mul( DAY_IN_SECONDS ); uint256 withdrawAmount; if (now >= stakeObj.stakeTimestamp.add(stakeTimeInSeconds)) { // matured, withdraw all withdrawAmount = stakeObj .stakeAmount .add(stakeObj.interestAmount) .sub(stakeObj.withdrawnInterestAmount); stakeObj.active = false; stakeObj.withdrawnInterestAmount = stakeObj.interestAmount; userStakeAmount[msg.sender] = userStakeAmount[msg.sender].sub( stakeObj.stakeAmount ); emit WithdrawReward( stakeIdx, msg.sender, stakeObj.interestAmount.sub(stakeObj.withdrawnInterestAmount) ); emit WithdrawStake(stakeIdx, msg.sender); } else { // not mature, partial withdraw withdrawAmount = stakeObj .interestAmount .mul(uint256(now).sub(stakeObj.stakeTimestamp)) .div(stakeTimeInSeconds) .sub(stakeObj.withdrawnInterestAmount); // record withdrawal stakeObj.withdrawnInterestAmount = stakeObj .withdrawnInterestAmount .add(withdrawAmount); emit WithdrawReward(stakeIdx, msg.sender, withdrawAmount); } // withdraw interest to sender peakToken.safeTransfer(msg.sender, withdrawAmount); } function getInterestAmount(uint256 stakeAmount, uint256 stakeTimeInDays) public view returns (uint256) { uint256 earlyFactor = _earlyFactor(mintedPeakTokens); uint256 biggerBonus = stakeAmount.mul(PRECISION).div( BIGGER_BONUS_DIVISOR ); if (biggerBonus > MAX_BIGGER_BONUS) { biggerBonus = MAX_BIGGER_BONUS; } // convert yearly bigger bonus to stake time biggerBonus = biggerBonus.mul(stakeTimeInDays).div(YEAR_IN_DAYS); uint256 longerBonus = _longerBonus(stakeTimeInDays); uint256 interestRate = biggerBonus.add(longerBonus).mul(earlyFactor).div( PRECISION ); uint256 interestAmount = stakeAmount.mul(interestRate).div(PRECISION); return interestAmount; } function _longerBonus(uint256 stakeTimeInDays) internal pure returns (uint256) { return DAILY_BASE_REWARD.mul(stakeTimeInDays).add( DAILY_GROWING_REWARD .mul(stakeTimeInDays) .mul(stakeTimeInDays.add(1)) .div(2) ); } function _earlyFactor(uint256 _mintedPeakTokens) internal pure returns (uint256) { uint256 tmp = INTEREST_SLOPE.mul(_mintedPeakTokens).div(PEAK_PRECISION); if (tmp > PRECISION) { return 0; } return PRECISION.sub(tmp); } } pragma solidity 0.5.17; import "./lib/CloneFactory.sol"; import "./tokens/minime/MiniMeToken.sol"; import "./PeakDeFiFund.sol"; import "./PeakDeFiProxy.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract PeakDeFiFactory is CloneFactory { using Address for address; event CreateFund(address fund); event InitFund(address fund, address proxy); address public usdcAddr; address payable public kyberAddr; address payable public oneInchAddr; address payable public peakdefiFund; address public peakdefiLogic; address public peakdefiLogic2; address public peakdefiLogic3; address public peakRewardAddr; address public peakStakingAddr; MiniMeTokenFactory public minimeFactory; mapping(address => address) public fundCreator; constructor( address _usdcAddr, address payable _kyberAddr, address payable _oneInchAddr, address payable _peakdefiFund, address _peakdefiLogic, address _peakdefiLogic2, address _peakdefiLogic3, address _peakRewardAddr, address _peakStakingAddr, address _minimeFactoryAddr ) public { usdcAddr = _usdcAddr; kyberAddr = _kyberAddr; oneInchAddr = _oneInchAddr; peakdefiFund = _peakdefiFund; peakdefiLogic = _peakdefiLogic; peakdefiLogic2 = _peakdefiLogic2; peakdefiLogic3 = _peakdefiLogic3; peakRewardAddr = _peakRewardAddr; peakStakingAddr = _peakStakingAddr; minimeFactory = MiniMeTokenFactory(_minimeFactoryAddr); } function createFund() external returns (PeakDeFiFund) { // create fund PeakDeFiFund fund = PeakDeFiFund(createClone(peakdefiFund).toPayable()); fund.initOwner(); // give PeakReward signer rights to fund PeakReward peakReward = PeakReward(peakRewardAddr); peakReward.addSigner(address(fund)); fundCreator[address(fund)] = msg.sender; emit CreateFund(address(fund)); return fund; } function initFund1( PeakDeFiFund fund, string calldata reptokenName, string calldata reptokenSymbol, string calldata sharesName, string calldata sharesSymbol ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); // create tokens MiniMeToken reptoken = minimeFactory.createCloneToken( address(0), 0, reptokenName, 18, reptokenSymbol, false ); MiniMeToken shares = minimeFactory.createCloneToken( address(0), 0, sharesName, 18, sharesSymbol, true ); MiniMeToken peakReferralToken = minimeFactory.createCloneToken( address(0), 0, "Peak Referral Token", 18, "PRT", false ); // transfer token ownerships to fund reptoken.transferOwnership(address(fund)); shares.transferOwnership(address(fund)); peakReferralToken.transferOwnership(address(fund)); fund.initInternalTokens( address(reptoken), address(shares), address(peakReferralToken) ); } function initFund2( PeakDeFiFund fund, address payable _devFundingAccount, uint256 _devFundingRate, uint256[2] calldata _phaseLengths, address _compoundFactoryAddr ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); fund.initParams( _devFundingAccount, _phaseLengths, _devFundingRate, address(0), usdcAddr, kyberAddr, _compoundFactoryAddr, peakdefiLogic, peakdefiLogic2, peakdefiLogic3, 1, oneInchAddr, peakRewardAddr, peakStakingAddr ); } function initFund3( PeakDeFiFund fund, uint256 _newManagerRepToken, uint256 _maxNewManagersPerCycle, uint256 _reptokenPrice, uint256 _peakManagerStakeRequired, bool _isPermissioned ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); fund.initRegistration( _newManagerRepToken, _maxNewManagersPerCycle, _reptokenPrice, _peakManagerStakeRequired, _isPermissioned ); } function initFund4( PeakDeFiFund fund, address[] calldata _kyberTokens, address[] calldata _compoundTokens ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); fund.initTokenListings(_kyberTokens, _compoundTokens); // deploy and set PeakDeFiProxy PeakDeFiProxy proxy = new PeakDeFiProxy(address(fund)); fund.setProxy(address(proxy).toPayable()); // transfer fund ownership to msg.sender fund.transferOwnership(msg.sender); emit InitFund(address(fund), address(proxy)); } } pragma solidity 0.5.17; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./TokenController.sol"; contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public; } /// @dev The actual token contract, the default owner is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token owner contract, which Giveth will call a "Campaign" contract MiniMeToken is Ownable { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.2"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred constructor( address _tokenFactory, address payable _parentToken, uint _parentSnapShotBlock, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { // The owner of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // owner of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != owner()) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != address(0)) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // Alerts the token owner of the transfer if (isContract(owner())) { require(TokenController(owner()).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token owner of the approve function call if (isContract(owner())) { require(TokenController(owner()).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes memory _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, address(this), _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public view returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != address(0)) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public view returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != address(0)) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string memory _cloneTokenName, uint8 _cloneDecimalUnits, string memory _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { uint snapshotBlock = _snapshotBlock; if (snapshotBlock == 0) snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( address(this), snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.transferOwnership(msg.sender); // An event to make the token easy to find on the blockchain emit NewCloneToken(address(cloneToken), snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) public onlyOwner returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); emit Transfer(address(0), _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyOwner public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); emit Transfer(_owner, address(0), _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyOwner { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) view internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) view internal returns(bool) { uint size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's owner has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token owner contract function () external payable { require(isContract(owner())); require(TokenController(owner()).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address payable _token) public onlyOwner { if (_token == address(0)) { address(uint160(owner())).transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(address(this)); require(token.transfer(owner(), balance)); emit ClaimedTokens(_token, owner(), balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { event CreatedToken(string symbol, address addr); /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the owner of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address payable _parentToken, uint _snapshotBlock, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( address(this), _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.transferOwnership(msg.sender); emit CreatedToken(_tokenSymbol, address(newToken)); return newToken; } } pragma solidity 0.5.17; /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } pragma solidity 0.5.17; import "./PeakDeFiStorage.sol"; import "./derivatives/CompoundOrderFactory.sol"; /** * @title The main smart contract of the PeakDeFi hedge fund. * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiFund is PeakDeFiStorage, Utils(address(0), address(0), address(0)), TokenController { /** * @notice Passes if the fund is ready for migrating to the next version */ modifier readyForUpgradeMigration { require(hasFinalizedNextVersion == true); require( now > startTimeOfCyclePhase.add( phaseLengths[uint256(CyclePhase.Intermission)] ) ); _; } /** * Meta functions */ function initParams( address payable _devFundingAccount, uint256[2] calldata _phaseLengths, uint256 _devFundingRate, address payable _previousVersion, address _usdcAddr, address payable _kyberAddr, address _compoundFactoryAddr, address _peakdefiLogic, address _peakdefiLogic2, address _peakdefiLogic3, uint256 _startCycleNumber, address payable _oneInchAddr, address _peakRewardAddr, address _peakStakingAddr ) external { require(proxyAddr == address(0)); devFundingAccount = _devFundingAccount; phaseLengths = _phaseLengths; devFundingRate = _devFundingRate; cyclePhase = CyclePhase.Intermission; compoundFactoryAddr = _compoundFactoryAddr; peakdefiLogic = _peakdefiLogic; peakdefiLogic2 = _peakdefiLogic2; peakdefiLogic3 = _peakdefiLogic3; previousVersion = _previousVersion; cycleNumber = _startCycleNumber; peakReward = PeakReward(_peakRewardAddr); peakStaking = PeakStaking(_peakStakingAddr); USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; ONEINCH_ADDR = _oneInchAddr; usdc = ERC20Detailed(_usdcAddr); kyber = KyberNetwork(_kyberAddr); __initReentrancyGuard(); } function initOwner() external { require(proxyAddr == address(0)); _transferOwnership(msg.sender); } function initInternalTokens( address payable _repAddr, address payable _sTokenAddr, address payable _peakReferralTokenAddr ) external onlyOwner { require(controlTokenAddr == address(0)); require(_repAddr != address(0)); controlTokenAddr = _repAddr; shareTokenAddr = _sTokenAddr; cToken = IMiniMeToken(_repAddr); sToken = IMiniMeToken(_sTokenAddr); peakReferralToken = IMiniMeToken(_peakReferralTokenAddr); } function initRegistration( uint256 _newManagerRepToken, uint256 _maxNewManagersPerCycle, uint256 _reptokenPrice, uint256 _peakManagerStakeRequired, bool _isPermissioned ) external onlyOwner { require(_newManagerRepToken > 0 && newManagerRepToken == 0); newManagerRepToken = _newManagerRepToken; maxNewManagersPerCycle = _maxNewManagersPerCycle; reptokenPrice = _reptokenPrice; peakManagerStakeRequired = _peakManagerStakeRequired; isPermissioned = _isPermissioned; } function initTokenListings( address[] calldata _kyberTokens, address[] calldata _compoundTokens ) external onlyOwner { // May only initialize once require(!hasInitializedTokenListings); hasInitializedTokenListings = true; uint256 i; for (i = 0; i < _kyberTokens.length; i++) { isKyberToken[_kyberTokens[i]] = true; } CompoundOrderFactory factory = CompoundOrderFactory(compoundFactoryAddr); for (i = 0; i < _compoundTokens.length; i++) { require(factory.tokenIsListed(_compoundTokens[i])); isCompoundToken[_compoundTokens[i]] = true; } } /** * @notice Used during deployment to set the PeakDeFiProxy contract address. * @param _proxyAddr the proxy's address */ function setProxy(address payable _proxyAddr) external onlyOwner { require(_proxyAddr != address(0)); require(proxyAddr == address(0)); proxyAddr = _proxyAddr; proxy = PeakDeFiProxyInterface(_proxyAddr); } /** * Upgrading functions */ /** * @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to. * The developer may change the candidate during the Intermission phase. * @param _candidate the address of the candidate smart contract * @return True if successfully changed candidate, false otherwise. */ function developerInitiateUpgrade(address payable _candidate) public returns (bool _success) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.developerInitiateUpgrade.selector, _candidate ) ); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Transfers ownership of RepToken & Share token contracts to the next version. Also updates PeakDeFiFund's * address in PeakDeFiProxy. */ function migrateOwnedContractsToNextVersion() public nonReentrant readyForUpgradeMigration { cToken.transferOwnership(nextVersion); sToken.transferOwnership(nextVersion); peakReferralToken.transferOwnership(nextVersion); proxy.updatePeakDeFiFundAddress(); } /** * @notice Transfers assets to the next version. * @param _assetAddress the address of the asset to be transferred. Use ETH_TOKEN_ADDRESS to transfer Ether. */ function transferAssetToNextVersion(address _assetAddress) public nonReentrant readyForUpgradeMigration isValidToken(_assetAddress) { if (_assetAddress == address(ETH_TOKEN_ADDRESS)) { nextVersion.transfer(address(this).balance); } else { ERC20Detailed token = ERC20Detailed(_assetAddress); token.safeTransfer(nextVersion, token.balanceOf(address(this))); } } /** * Getters */ /** * @notice Returns the length of the user's investments array. * @return length of the user's investments array */ function investmentsCount(address _userAddr) public view returns (uint256 _count) { return userInvestments[_userAddr].length; } /** * @notice Returns the length of the user's compound orders array. * @return length of the user's compound orders array */ function compoundOrdersCount(address _userAddr) public view returns (uint256 _count) { return userCompoundOrders[_userAddr].length; } /** * @notice Returns the phaseLengths array. * @return the phaseLengths array */ function getPhaseLengths() public view returns (uint256[2] memory _phaseLengths) { return phaseLengths; } /** * @notice Returns the commission balance of `_manager` * @return the commission balance and the received penalty, denoted in USDC */ function commissionBalanceOf(address _manager) public returns (uint256 _commission, uint256 _penalty) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.commissionBalanceOf.selector, _manager) ); if (!success) { return (0, 0); } return abi.decode(result, (uint256, uint256)); } /** * @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle * @return the commission amount and the received penalty, denoted in USDC */ function commissionOfAt(address _manager, uint256 _cycle) public returns (uint256 _commission, uint256 _penalty) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.commissionOfAt.selector, _manager, _cycle ) ); if (!success) { return (0, 0); } return abi.decode(result, (uint256, uint256)); } /** * Parameter setters */ /** * @notice Changes the address to which the developer fees will be sent. Only callable by owner. * @param _newAddr the new developer fee address */ function changeDeveloperFeeAccount(address payable _newAddr) public onlyOwner { require(_newAddr != address(0) && _newAddr != address(this)); devFundingAccount = _newAddr; } /** * @notice Changes the proportion of fund balance sent to the developers each cycle. May only decrease. Only callable by owner. * @param _newProp the new proportion, fixed point decimal */ function changeDeveloperFeeRate(uint256 _newProp) public onlyOwner { require(_newProp < PRECISION); require(_newProp < devFundingRate); devFundingRate = _newProp; } /** * @notice Allows managers to invest in a token. Only callable by owner. * @param _token address of the token to be listed */ function listKyberToken(address _token) public onlyOwner { isKyberToken[_token] = true; } /** * @notice Allows managers to invest in a Compound token. Only callable by owner. * @param _token address of the Compound token to be listed */ function listCompoundToken(address _token) public onlyOwner { CompoundOrderFactory factory = CompoundOrderFactory( compoundFactoryAddr ); require(factory.tokenIsListed(_token)); isCompoundToken[_token] = true; } /** * @notice Moves the fund to the next phase in the investment cycle. */ function nextPhase() public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.nextPhase.selector) ); if (!success) { revert(); } } /** * Manager registration */ /** * @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithUSDC() public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.registerWithUSDC.selector) ); if (!success) { revert(); } } /** * @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithETH() public payable { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.registerWithETH.selector) ); if (!success) { revert(); } } /** * @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. * @param _token the token to be used for payment * @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals */ function registerWithToken(address _token, uint256 _donationInTokens) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.registerWithToken.selector, _token, _donationInTokens ) ); if (!success) { revert(); } } /** * Intermission phase functions */ /** * @notice Deposit Ether into the fund. Ether will be converted into USDC. */ function depositEther(address _referrer) public payable { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.depositEther.selector, _referrer) ); if (!success) { revert(); } } function depositEtherAdvanced( bool _useKyber, bytes calldata _calldata, address _referrer ) external payable { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositEtherAdvanced.selector, _useKyber, _calldata, _referrer ) ); if (!success) { revert(); } } /** * @notice Deposit USDC Stablecoin into the fund. * @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount. */ function depositUSDC(uint256 _usdcAmount, address _referrer) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositUSDC.selector, _usdcAmount, _referrer ) ); if (!success) { revert(); } } /** * @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC. * @param _tokenAddr the address of the token to be deposited * @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount. */ function depositToken( address _tokenAddr, uint256 _tokenAmount, address _referrer ) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositToken.selector, _tokenAddr, _tokenAmount, _referrer ) ); if (!success) { revert(); } } function depositTokenAdvanced( address _tokenAddr, uint256 _tokenAmount, bool _useKyber, bytes calldata _calldata, address _referrer ) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositTokenAdvanced.selector, _tokenAddr, _tokenAmount, _useKyber, _calldata, _referrer ) ); if (!success) { revert(); } } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawEther(uint256 _amountInUSDC) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.withdrawEther.selector, _amountInUSDC) ); if (!success) { revert(); } } function withdrawEtherAdvanced( uint256 _amountInUSDC, bool _useKyber, bytes calldata _calldata ) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.withdrawEtherAdvanced.selector, _amountInUSDC, _useKyber, _calldata ) ); if (!success) { revert(); } } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawUSDC(uint256 _amountInUSDC) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.withdrawUSDC.selector, _amountInUSDC) ); if (!success) { revert(); } } /** * @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network. * @param _tokenAddr the address of the token to be withdrawn into the caller's account * @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.withdrawToken.selector, _tokenAddr, _amountInUSDC ) ); if (!success) { revert(); } } function withdrawTokenAdvanced( address _tokenAddr, uint256 _amountInUSDC, bool _useKyber, bytes calldata _calldata ) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.withdrawTokenAdvanced.selector, _tokenAddr, _amountInUSDC, _useKyber, _calldata ) ); if (!success) { revert(); } } /** * @notice Redeems commission. */ function redeemCommission(bool _inShares) public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.redeemCommission.selector, _inShares) ); if (!success) { revert(); } } /** * @notice Redeems commission for a particular cycle. * @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function redeemCommissionForCycle(bool _inShares, uint256 _cycle) public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.redeemCommissionForCycle.selector, _inShares, _cycle ) ); if (!success) { revert(); } } /** * @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _tokenAddr address of the token to be sold * @param _calldata the 1inch trade call data */ function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.sellLeftoverToken.selector, _tokenAddr, _calldata ) ); if (!success) { revert(); } } /** * @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _orderAddress address of the CompoundOrder to be sold */ function sellLeftoverCompoundOrder(address payable _orderAddress) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.sellLeftoverCompoundOrder.selector, _orderAddress ) ); if (!success) { revert(); } } /** * @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles * @param _deadman the manager whose RepToken balance will be burned */ function burnDeadman(address _deadman) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector(this.burnDeadman.selector, _deadman) ); if (!success) { revert(); } } /** * Manage phase functions */ function createInvestmentWithSignature( address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createInvestmentWithSignature.selector, _tokenAddress, _stake, _maxPrice, _calldata, _useKyber, _manager, _salt, _signature ) ); if (!success) { revert(); } } function sellInvestmentWithSignature( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, uint256 _maxPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellInvestmentWithSignature.selector, _investmentId, _tokenAmount, _minPrice, _maxPrice, _calldata, _useKyber, _manager, _salt, _signature ) ); if (!success) { revert(); } } function createCompoundOrderWithSignature( bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createCompoundOrderWithSignature.selector, _orderType, _tokenAddress, _stake, _minPrice, _maxPrice, _manager, _salt, _signature ) ); if (!success) { revert(); } } function sellCompoundOrderWithSignature( uint256 _orderId, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellCompoundOrderWithSignature.selector, _orderId, _minPrice, _maxPrice, _manager, _salt, _signature ) ); if (!success) { revert(); } } function repayCompoundOrderWithSignature( uint256 _orderId, uint256 _repayAmountInUSDC, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.repayCompoundOrderWithSignature.selector, _orderId, _repayAmountInUSDC, _manager, _salt, _signature ) ); if (!success) { revert(); } } /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade */ function createInvestment( address _tokenAddress, uint256 _stake, uint256 _maxPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createInvestment.selector, _tokenAddress, _stake, _maxPrice ) ); if (!success) { revert(); } } /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade * @param _calldata calldata for 1inch trading * @param _useKyber true for Kyber Network, false for 1inch */ function createInvestmentV2( address _sender, address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes memory _calldata, bool _useKyber ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createInvestmentV2.selector, _sender, _tokenAddress, _stake, _maxPrice, _calldata, _useKyber ) ); if (!success) { revert(); } } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAsset( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellInvestmentAsset.selector, _investmentId, _tokenAmount, _minPrice ) ); if (!success) { revert(); } } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAssetV2( address _sender, uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, bytes memory _calldata, bool _useKyber ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellInvestmentAssetV2.selector, _sender, _investmentId, _tokenAmount, _minPrice, _calldata, _useKyber ) ); if (!success) { revert(); } } /** * @notice Creates a new Compound order to either short or leverage long a token. * @param _orderType true for a short order, false for a levarage long order * @param _tokenAddress address of the Compound token to be traded * @param _stake amount of RepTokens to be staked * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function createCompoundOrder( address _sender, bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createCompoundOrder.selector, _sender, _orderType, _tokenAddress, _stake, _minPrice, _maxPrice ) ); if (!success) { revert(); } } /** * @notice Sells a compound order * @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender]) * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function sellCompoundOrder( address _sender, uint256 _orderId, uint256 _minPrice, uint256 _maxPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellCompoundOrder.selector, _sender, _orderId, _minPrice, _maxPrice ) ); if (!success) { revert(); } } /** * @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold. * @param _orderId the ID of the Compound order * @param _repayAmountInUSDC amount of USDC to use for repaying debt */ function repayCompoundOrder( address _sender, uint256 _orderId, uint256 _repayAmountInUSDC ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.repayCompoundOrder.selector, _sender, _orderId, _repayAmountInUSDC ) ); if (!success) { revert(); } } /** * @notice Emergency exit the tokens from order contract during intermission stage * @param _sender the address of trader, who created the order * @param _orderId the ID of the Compound order * @param _tokenAddr the address of token which should be transferred * @param _receiver the address of receiver */ function emergencyExitCompoundTokens( address _sender, uint256 _orderId, address _tokenAddr, address _receiver ) public onlyOwner { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.emergencyExitCompoundTokens.selector, _sender, _orderId, _tokenAddr, _receiver ) ); if (!success) { revert(); } } /** * Internal use functions */ // MiniMe TokenController functions, not used right now /** * @notice Called when `_owner` sends ether to the MiniMe Token contract * @return True if the ether is accepted, false if it throws */ function proxyPayment( address /*_owner*/ ) public payable returns (bool) { return false; } /** * @notice Notifies the controller about a token transfer allowing the * controller to react if desired * @return False if the controller does not authorize the transfer */ function onTransfer( address, /*_from*/ address, /*_to*/ uint256 /*_amount*/ ) public returns (bool) { return true; } /** * @notice Notifies the controller about an approval allowing the * controller to react if desired * @return False if the controller does not authorize the approval */ function onApprove( address, /*_owner*/ address, /*_spender*/ uint256 /*_amount*/ ) public returns (bool) { return true; } function() external payable {} /** PeakDeFi */ /** * @notice Returns the commission balance of `_referrer` * @return the commission balance and the received penalty, denoted in USDC */ function peakReferralCommissionBalanceOf(address _referrer) public returns (uint256 _commission) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.peakReferralCommissionBalanceOf.selector, _referrer ) ); if (!success) { return 0; } return abi.decode(result, (uint256)); } /** * @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle * @return the commission amount and the received penalty, denoted in USDC */ function peakReferralCommissionOfAt(address _referrer, uint256 _cycle) public returns (uint256 _commission) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.peakReferralCommissionOfAt.selector, _referrer, _cycle ) ); if (!success) { return 0; } return abi.decode(result, (uint256)); } /** * @notice Redeems commission. */ function peakReferralRedeemCommission() public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.peakReferralRedeemCommission.selector) ); if (!success) { revert(); } } /** * @notice Redeems commission for a particular cycle. * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function peakReferralRedeemCommissionForCycle(uint256 _cycle) public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.peakReferralRedeemCommissionForCycle.selector, _cycle ) ); if (!success) { revert(); } } /** * @notice Changes the required PEAK stake of a new manager. Only callable by owner. * @param _newValue the new value */ function peakChangeManagerStakeRequired(uint256 _newValue) public onlyOwner { peakManagerStakeRequired = _newValue; } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./lib/ReentrancyGuard.sol"; import "./interfaces/IMiniMeToken.sol"; import "./tokens/minime/TokenController.sol"; import "./Utils.sol"; import "./PeakDeFiProxyInterface.sol"; import "./peak/reward/PeakReward.sol"; import "./peak/staking/PeakStaking.sol"; /** * @title The storage layout of PeakDeFiFund * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiStorage is Ownable, ReentrancyGuard { using SafeMath for uint256; enum CyclePhase {Intermission, Manage} enum VoteDirection {Empty, For, Against} enum Subchunk {Propose, Vote} struct Investment { address tokenAddress; uint256 cycleNumber; uint256 stake; uint256 tokenAmount; uint256 buyPrice; // token buy price in 18 decimals in USDC uint256 sellPrice; // token sell price in 18 decimals in USDC uint256 buyTime; uint256 buyCostInUSDC; bool isSold; } // Fund parameters uint256 public constant COMMISSION_RATE = 15 * (10**16); // The proportion of profits that gets distributed to RepToken holders every cycle. uint256 public constant ASSET_FEE_RATE = 1 * (10**15); // The proportion of fund balance that gets distributed to RepToken holders every cycle. uint256 public constant NEXT_PHASE_REWARD = 1 * (10**18); // Amount of RepToken rewarded to the user who calls nextPhase(). uint256 public constant COLLATERAL_RATIO_MODIFIER = 75 * (10**16); // Modifies Compound's collateral ratio, gets 2:1 from 1.5:1 ratio uint256 public constant MIN_RISK_TIME = 3 days; // Mininum risk taken to get full commissions is 9 days * reptokenBalance uint256 public constant INACTIVE_THRESHOLD = 2; // Number of inactive cycles after which a manager's RepToken balance can be burned uint256 public constant ROI_PUNISH_THRESHOLD = 1 * (10**17); // ROI worse than 10% will see punishment in stake uint256 public constant ROI_BURN_THRESHOLD = 25 * (10**16); // ROI worse than 25% will see their stake all burned uint256 public constant ROI_PUNISH_SLOPE = 6; // repROI = -(6 * absROI - 0.5) uint256 public constant ROI_PUNISH_NEG_BIAS = 5 * (10**17); // repROI = -(6 * absROI - 0.5) uint256 public constant PEAK_COMMISSION_RATE = 20 * (10**16); // The proportion of profits that gets distributed to PeakDeFi referrers every cycle. // Instance variables // Checks if the token listing initialization has been completed. bool public hasInitializedTokenListings; // Checks if the fund has been initialized bool public isInitialized; // Address of the RepToken token contract. address public controlTokenAddr; // Address of the share token contract. address public shareTokenAddr; // Address of the PeakDeFiProxy contract. address payable public proxyAddr; // Address of the CompoundOrderFactory contract. address public compoundFactoryAddr; // Address of the PeakDeFiLogic contract. address public peakdefiLogic; address public peakdefiLogic2; address public peakdefiLogic3; // Address to which the development team funding will be sent. address payable public devFundingAccount; // Address of the previous version of PeakDeFiFund. address payable public previousVersion; // The number of the current investment cycle. uint256 public cycleNumber; // The amount of funds held by the fund. uint256 public totalFundsInUSDC; // The total funds at the beginning of the current management phase uint256 public totalFundsAtManagePhaseStart; // The start time for the current investment cycle phase, in seconds since Unix epoch. uint256 public startTimeOfCyclePhase; // The proportion of PeakDeFi Shares total supply to mint and use for funding the development team. Fixed point decimal. uint256 public devFundingRate; // Total amount of commission unclaimed by managers uint256 public totalCommissionLeft; // Stores the lengths of each cycle phase in seconds. uint256[2] public phaseLengths; // The number of managers onboarded during the current cycle uint256 public managersOnboardedThisCycle; // The amount of RepToken tokens a new manager receves uint256 public newManagerRepToken; // The max number of new managers that can be onboarded in one cycle uint256 public maxNewManagersPerCycle; // The price of RepToken in USDC uint256 public reptokenPrice; // The last cycle where a user redeemed all of their remaining commission. mapping(address => uint256) internal _lastCommissionRedemption; // Marks whether a manager has redeemed their commission for a certain cycle mapping(address => mapping(uint256 => bool)) internal _hasRedeemedCommissionForCycle; // The stake-time measured risk that a manager has taken in a cycle mapping(address => mapping(uint256 => uint256)) internal _riskTakenInCycle; // In case a manager joined the fund during the current cycle, set the fallback base stake for risk threshold calculation mapping(address => uint256) internal _baseRiskStakeFallback; // List of investments of a manager in the current cycle. mapping(address => Investment[]) public userInvestments; // List of short/long orders of a manager in the current cycle. mapping(address => address payable[]) public userCompoundOrders; // Total commission to be paid for work done in a certain cycle (will be redeemed in the next cycle's Intermission) mapping(uint256 => uint256) internal _totalCommissionOfCycle; // The block number at which the Manage phase ended for a given cycle mapping(uint256 => uint256) internal _managePhaseEndBlock; // The last cycle where a manager made an investment mapping(address => uint256) internal _lastActiveCycle; // Checks if an address points to a whitelisted Kyber token. mapping(address => bool) public isKyberToken; // Checks if an address points to a whitelisted Compound token. Returns false for cUSDC and other stablecoin CompoundTokens. mapping(address => bool) public isCompoundToken; // The current cycle phase. CyclePhase public cyclePhase; // Upgrade governance related variables bool public hasFinalizedNextVersion; // Denotes if the address of the next smart contract version has been finalized address payable public nextVersion; // Address of the next version of PeakDeFiFund. // Contract instances IMiniMeToken internal cToken; IMiniMeToken internal sToken; PeakDeFiProxyInterface internal proxy; // PeakDeFi uint256 public peakReferralTotalCommissionLeft; uint256 public peakManagerStakeRequired; mapping(uint256 => uint256) internal _peakReferralTotalCommissionOfCycle; mapping(address => uint256) internal _peakReferralLastCommissionRedemption; mapping(address => mapping(uint256 => bool)) internal _peakReferralHasRedeemedCommissionForCycle; IMiniMeToken public peakReferralToken; PeakReward public peakReward; PeakStaking public peakStaking; bool public isPermissioned; mapping(address => mapping(uint256 => bool)) public hasUsedSalt; // Events event ChangedPhase( uint256 indexed _cycleNumber, uint256 indexed _newPhase, uint256 _timestamp, uint256 _totalFundsInUSDC ); event Deposit( uint256 indexed _cycleNumber, address indexed _sender, address _tokenAddress, uint256 _tokenAmount, uint256 _usdcAmount, uint256 _timestamp ); event Withdraw( uint256 indexed _cycleNumber, address indexed _sender, address _tokenAddress, uint256 _tokenAmount, uint256 _usdcAmount, uint256 _timestamp ); event CreatedInvestment( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _tokenAddress, uint256 _stakeInWeis, uint256 _buyPrice, uint256 _costUSDCAmount, uint256 _tokenAmount ); event SoldInvestment( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _tokenAddress, uint256 _receivedRepToken, uint256 _sellPrice, uint256 _earnedUSDCAmount ); event CreatedCompoundOrder( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, bool _orderType, address _tokenAddress, uint256 _stakeInWeis, uint256 _costUSDCAmount ); event SoldCompoundOrder( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, bool _orderType, address _tokenAddress, uint256 _receivedRepToken, uint256 _earnedUSDCAmount ); event RepaidCompoundOrder( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, uint256 _repaidUSDCAmount ); event CommissionPaid( uint256 indexed _cycleNumber, address indexed _sender, uint256 _commission ); event TotalCommissionPaid( uint256 indexed _cycleNumber, uint256 _totalCommissionInUSDC ); event Register( address indexed _manager, uint256 _donationInUSDC, uint256 _reptokenReceived ); event BurnDeadman(address indexed _manager, uint256 _reptokenBurned); event DeveloperInitiatedUpgrade( uint256 indexed _cycleNumber, address _candidate ); event FinalizedNextVersion( uint256 indexed _cycleNumber, address _nextVersion ); event PeakReferralCommissionPaid( uint256 indexed _cycleNumber, address indexed _sender, uint256 _commission ); event PeakReferralTotalCommissionPaid( uint256 indexed _cycleNumber, uint256 _totalCommissionInUSDC ); /* Helper functions shared by both PeakDeFiLogic & PeakDeFiFund */ function lastCommissionRedemption(address _manager) public view returns (uint256) { if (_lastCommissionRedemption[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).lastCommissionRedemption( _manager ); } return _lastCommissionRedemption[_manager]; } function hasRedeemedCommissionForCycle(address _manager, uint256 _cycle) public view returns (bool) { if (_hasRedeemedCommissionForCycle[_manager][_cycle] == false) { return previousVersion == address(0) ? false : PeakDeFiStorage(previousVersion) .hasRedeemedCommissionForCycle(_manager, _cycle); } return _hasRedeemedCommissionForCycle[_manager][_cycle]; } function riskTakenInCycle(address _manager, uint256 _cycle) public view returns (uint256) { if (_riskTakenInCycle[_manager][_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).riskTakenInCycle( _manager, _cycle ); } return _riskTakenInCycle[_manager][_cycle]; } function baseRiskStakeFallback(address _manager) public view returns (uint256) { if (_baseRiskStakeFallback[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).baseRiskStakeFallback( _manager ); } return _baseRiskStakeFallback[_manager]; } function totalCommissionOfCycle(uint256 _cycle) public view returns (uint256) { if (_totalCommissionOfCycle[_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).totalCommissionOfCycle( _cycle ); } return _totalCommissionOfCycle[_cycle]; } function managePhaseEndBlock(uint256 _cycle) public view returns (uint256) { if (_managePhaseEndBlock[_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).managePhaseEndBlock( _cycle ); } return _managePhaseEndBlock[_cycle]; } function lastActiveCycle(address _manager) public view returns (uint256) { if (_lastActiveCycle[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).lastActiveCycle(_manager); } return _lastActiveCycle[_manager]; } /** PeakDeFi */ function peakReferralLastCommissionRedemption(address _manager) public view returns (uint256) { if (_peakReferralLastCommissionRedemption[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion) .peakReferralLastCommissionRedemption(_manager); } return _peakReferralLastCommissionRedemption[_manager]; } function peakReferralHasRedeemedCommissionForCycle( address _manager, uint256 _cycle ) public view returns (bool) { if ( _peakReferralHasRedeemedCommissionForCycle[_manager][_cycle] == false ) { return previousVersion == address(0) ? false : PeakDeFiStorage(previousVersion) .peakReferralHasRedeemedCommissionForCycle( _manager, _cycle ); } return _peakReferralHasRedeemedCommissionForCycle[_manager][_cycle]; } function peakReferralTotalCommissionOfCycle(uint256 _cycle) public view returns (uint256) { if (_peakReferralTotalCommissionOfCycle[_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion) .peakReferralTotalCommissionOfCycle(_cycle); } return _peakReferralTotalCommissionOfCycle[_cycle]; } } pragma solidity 0.5.17; interface PeakDeFiProxyInterface { function peakdefiFundAddress() external view returns (address payable); function updatePeakDeFiFundAddress() external; } pragma solidity 0.5.17; import "./PeakDeFiFund.sol"; contract PeakDeFiProxy { address payable public peakdefiFundAddress; event UpdatedFundAddress(address payable _newFundAddr); constructor(address payable _fundAddr) public { peakdefiFundAddress = _fundAddr; emit UpdatedFundAddress(_fundAddr); } function updatePeakDeFiFundAddress() public { require(msg.sender == peakdefiFundAddress, "Sender not PeakDeFiFund"); address payable nextVersion = PeakDeFiFund(peakdefiFundAddress) .nextVersion(); require(nextVersion != address(0), "Next version can't be empty"); peakdefiFundAddress = nextVersion; emit UpdatedFundAddress(peakdefiFundAddress); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "./PeakDeFiStorage.sol"; import "./derivatives/CompoundOrderFactory.sol"; /** * @title Part of the functions for PeakDeFiFund * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiLogic is PeakDeFiStorage, Utils(address(0), address(0), address(0)) { /** * @notice Executes function only during the given cycle phase. * @param phase the cycle phase during which the function may be called */ modifier during(CyclePhase phase) { require(cyclePhase == phase); if (cyclePhase == CyclePhase.Intermission) { require(isInitialized); } _; } /** * @notice Returns the length of the user's investments array. * @return length of the user's investments array */ function investmentsCount(address _userAddr) public view returns (uint256 _count) { return userInvestments[_userAddr].length; } /** * @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles * @param _deadman the manager whose RepToken balance will be burned */ function burnDeadman(address _deadman) public nonReentrant during(CyclePhase.Intermission) { require(_deadman != address(this)); require( cycleNumber.sub(lastActiveCycle(_deadman)) > INACTIVE_THRESHOLD ); uint256 balance = cToken.balanceOf(_deadman); require(cToken.destroyTokens(_deadman, balance)); emit BurnDeadman(_deadman, balance); } /** * @notice Creates a new investment for an ERC20 token. Backwards compatible. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade */ function createInvestment( address _tokenAddress, uint256 _stake, uint256 _maxPrice ) public { bytes memory nil; createInvestmentV2( msg.sender, _tokenAddress, _stake, _maxPrice, nil, true ); } function createInvestmentWithSignature( address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.createInvestmentWithSignature.selector, abi.encode( _tokenAddress, _stake, _maxPrice, _calldata, _useKyber ), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.createInvestmentV2( _manager, _tokenAddress, _stake, _maxPrice, _calldata, _useKyber ); } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. Backwards compatible. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAsset( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice ) public { bytes memory nil; sellInvestmentAssetV2( msg.sender, _investmentId, _tokenAmount, _minPrice, nil, true ); } function sellInvestmentWithSignature( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.sellInvestmentWithSignature.selector, abi.encode( _investmentId, _tokenAmount, _minPrice, _calldata, _useKyber ), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.sellInvestmentAssetV2( _manager, _investmentId, _tokenAmount, _minPrice, _calldata, _useKyber ); } /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade * @param _calldata calldata for 1inch trading * @param _useKyber true for Kyber Network, false for 1inch */ function createInvestmentV2( address _sender, address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes memory _calldata, bool _useKyber ) public during(CyclePhase.Manage) nonReentrant isValidToken(_tokenAddress) { require(msg.sender == _sender || msg.sender == address(this)); require(_stake > 0); require(isKyberToken[_tokenAddress]); // Verify user peak stake uint256 peakStake = peakStaking.userStakeAmount(_sender); require(peakStake >= peakManagerStakeRequired); // Collect stake require(cToken.generateTokens(address(this), _stake)); require(cToken.destroyTokens(_sender, _stake)); // Add investment to list userInvestments[_sender].push( Investment({ tokenAddress: _tokenAddress, cycleNumber: cycleNumber, stake: _stake, tokenAmount: 0, buyPrice: 0, sellPrice: 0, buyTime: now, buyCostInUSDC: 0, isSold: false }) ); // Invest uint256 investmentId = investmentsCount(_sender).sub(1); __handleInvestment( _sender, investmentId, 0, _maxPrice, true, _calldata, _useKyber ); // Update last active cycle _lastActiveCycle[_sender] = cycleNumber; // Emit event __emitCreatedInvestmentEvent(_sender, investmentId); } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAssetV2( address _sender, uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, bytes memory _calldata, bool _useKyber ) public nonReentrant during(CyclePhase.Manage) { require(msg.sender == _sender || msg.sender == address(this)); Investment storage investment = userInvestments[_sender][_investmentId]; require( investment.buyPrice > 0 && investment.cycleNumber == cycleNumber && !investment.isSold ); require(_tokenAmount > 0 && _tokenAmount <= investment.tokenAmount); // Create new investment for leftover tokens bool isPartialSell = false; uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div( investment.tokenAmount ); if (_tokenAmount != investment.tokenAmount) { isPartialSell = true; __createInvestmentForLeftovers( _sender, _investmentId, _tokenAmount ); __emitCreatedInvestmentEvent( _sender, investmentsCount(_sender).sub(1) ); } // Update investment info investment.isSold = true; // Sell asset ( uint256 actualDestAmount, uint256 actualSrcAmount ) = __handleInvestment( _sender, _investmentId, _minPrice, uint256(-1), false, _calldata, _useKyber ); __sellInvestmentUpdate( _sender, _investmentId, stakeOfSoldTokens, actualDestAmount ); } function __sellInvestmentUpdate( address _sender, uint256 _investmentId, uint256 stakeOfSoldTokens, uint256 actualDestAmount ) internal { Investment storage investment = userInvestments[_sender][_investmentId]; // Return staked RepToken uint256 receiveRepTokenAmount = getReceiveRepTokenAmount( stakeOfSoldTokens, investment.sellPrice, investment.buyPrice ); __returnStake(receiveRepTokenAmount, stakeOfSoldTokens); // Record risk taken in investment __recordRisk(_sender, investment.stake, investment.buyTime); // Update total funds totalFundsInUSDC = totalFundsInUSDC.sub(investment.buyCostInUSDC).add( actualDestAmount ); // Emit event __emitSoldInvestmentEvent( _sender, _investmentId, receiveRepTokenAmount, actualDestAmount ); } function __emitSoldInvestmentEvent( address _sender, uint256 _investmentId, uint256 _receiveRepTokenAmount, uint256 _actualDestAmount ) internal { Investment storage investment = userInvestments[_sender][_investmentId]; emit SoldInvestment( cycleNumber, _sender, _investmentId, investment.tokenAddress, _receiveRepTokenAmount, investment.sellPrice, _actualDestAmount ); } function __createInvestmentForLeftovers( address _sender, uint256 _investmentId, uint256 _tokenAmount ) internal { Investment storage investment = userInvestments[_sender][_investmentId]; uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div( investment.tokenAmount ); // calculate the part of original USDC cost attributed to the sold tokens uint256 soldBuyCostInUSDC = investment .buyCostInUSDC .mul(_tokenAmount) .div(investment.tokenAmount); userInvestments[_sender].push( Investment({ tokenAddress: investment.tokenAddress, cycleNumber: cycleNumber, stake: investment.stake.sub(stakeOfSoldTokens), tokenAmount: investment.tokenAmount.sub(_tokenAmount), buyPrice: investment.buyPrice, sellPrice: 0, buyTime: investment.buyTime, buyCostInUSDC: investment.buyCostInUSDC.sub(soldBuyCostInUSDC), isSold: false }) ); // update the investment object being sold investment.tokenAmount = _tokenAmount; investment.stake = stakeOfSoldTokens; investment.buyCostInUSDC = soldBuyCostInUSDC; } function __emitCreatedInvestmentEvent(address _sender, uint256 _id) internal { Investment storage investment = userInvestments[_sender][_id]; emit CreatedInvestment( cycleNumber, _sender, _id, investment.tokenAddress, investment.stake, investment.buyPrice, investment.buyCostInUSDC, investment.tokenAmount ); } function createCompoundOrderWithSignature( bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.createCompoundOrderWithSignature.selector, abi.encode( _orderType, _tokenAddress, _stake, _minPrice, _maxPrice ), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.createCompoundOrder( _manager, _orderType, _tokenAddress, _stake, _minPrice, _maxPrice ); } function sellCompoundOrderWithSignature( uint256 _orderId, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.sellCompoundOrderWithSignature.selector, abi.encode(_orderId, _minPrice, _maxPrice), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.sellCompoundOrder(_manager, _orderId, _minPrice, _maxPrice); } function repayCompoundOrderWithSignature( uint256 _orderId, uint256 _repayAmountInUSDC, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.repayCompoundOrderWithSignature.selector, abi.encode(_orderId, _repayAmountInUSDC), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.repayCompoundOrder(_manager, _orderId, _repayAmountInUSDC); } /** * @notice Creates a new Compound order to either short or leverage long a token. * @param _orderType true for a short order, false for a levarage long order * @param _tokenAddress address of the Compound token to be traded * @param _stake amount of RepTokens to be staked * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function createCompoundOrder( address _sender, bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice ) public during(CyclePhase.Manage) nonReentrant isValidToken(_tokenAddress) { require(msg.sender == _sender || msg.sender == address(this)); require(_minPrice <= _maxPrice); require(_stake > 0); require(isCompoundToken[_tokenAddress]); // Verify user peak stake uint256 peakStake = peakStaking.userStakeAmount(_sender); require(peakStake >= peakManagerStakeRequired); // Collect stake require(cToken.generateTokens(address(this), _stake)); require(cToken.destroyTokens(_sender, _stake)); // Create compound order and execute uint256 collateralAmountInUSDC = totalFundsInUSDC.mul(_stake).div( cToken.totalSupply() ); CompoundOrder order = __createCompoundOrder( _orderType, _tokenAddress, _stake, collateralAmountInUSDC ); usdc.safeApprove(address(order), 0); usdc.safeApprove(address(order), collateralAmountInUSDC); order.executeOrder(_minPrice, _maxPrice); // Add order to list userCompoundOrders[_sender].push(address(order)); // Update last active cycle _lastActiveCycle[_sender] = cycleNumber; __emitCreatedCompoundOrderEvent( _sender, address(order), _orderType, _tokenAddress, _stake, collateralAmountInUSDC ); } function __emitCreatedCompoundOrderEvent( address _sender, address order, bool _orderType, address _tokenAddress, uint256 _stake, uint256 collateralAmountInUSDC ) internal { // Emit event emit CreatedCompoundOrder( cycleNumber, _sender, userCompoundOrders[_sender].length - 1, address(order), _orderType, _tokenAddress, _stake, collateralAmountInUSDC ); } /** * @notice Sells a compound order * @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender]) * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function sellCompoundOrder( address _sender, uint256 _orderId, uint256 _minPrice, uint256 _maxPrice ) public during(CyclePhase.Manage) nonReentrant { require(msg.sender == _sender || msg.sender == address(this)); // Load order info require(userCompoundOrders[_sender][_orderId] != address(0)); CompoundOrder order = CompoundOrder( userCompoundOrders[_sender][_orderId] ); require(order.isSold() == false && order.cycleNumber() == cycleNumber); // Sell order (uint256 inputAmount, uint256 outputAmount) = order.sellOrder( _minPrice, _maxPrice ); // Return staked RepToken uint256 stake = order.stake(); uint256 receiveRepTokenAmount = getReceiveRepTokenAmount( stake, outputAmount, inputAmount ); __returnStake(receiveRepTokenAmount, stake); // Record risk taken __recordRisk(_sender, stake, order.buyTime()); // Update total funds totalFundsInUSDC = totalFundsInUSDC.sub(inputAmount).add(outputAmount); // Emit event emit SoldCompoundOrder( cycleNumber, _sender, userCompoundOrders[_sender].length - 1, address(order), order.orderType(), order.compoundTokenAddr(), receiveRepTokenAmount, outputAmount ); } /** * @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold. * @param _orderId the ID of the Compound order * @param _repayAmountInUSDC amount of USDC to use for repaying debt */ function repayCompoundOrder( address _sender, uint256 _orderId, uint256 _repayAmountInUSDC ) public during(CyclePhase.Manage) nonReentrant { require(msg.sender == _sender || msg.sender == address(this)); // Load order info require(userCompoundOrders[_sender][_orderId] != address(0)); CompoundOrder order = CompoundOrder( userCompoundOrders[_sender][_orderId] ); require(order.isSold() == false && order.cycleNumber() == cycleNumber); // Repay loan order.repayLoan(_repayAmountInUSDC); // Emit event emit RepaidCompoundOrder( cycleNumber, _sender, userCompoundOrders[_sender].length - 1, address(order), _repayAmountInUSDC ); } function emergencyExitCompoundTokens( address _sender, uint256 _orderId, address _tokenAddr, address _receiver ) public during(CyclePhase.Intermission) nonReentrant { CompoundOrder order = CompoundOrder(userCompoundOrders[_sender][_orderId]); order.emergencyExitTokens(_tokenAddr, _receiver); } function getReceiveRepTokenAmount( uint256 stake, uint256 output, uint256 input ) public pure returns (uint256 _amount) { if (output >= input) { // positive ROI, simply return stake * (1 + ROI) return stake.mul(output).div(input); } else { // negative ROI uint256 absROI = input.sub(output).mul(PRECISION).div(input); if (absROI <= ROI_PUNISH_THRESHOLD) { // ROI better than -10%, no punishment return stake.mul(output).div(input); } else if ( absROI > ROI_PUNISH_THRESHOLD && absROI < ROI_BURN_THRESHOLD ) { // ROI between -10% and -25%, punish // return stake * (1 + roiWithPunishment) = stake * (1 + (-(6 * absROI - 0.5))) return stake .mul( PRECISION.sub( ROI_PUNISH_SLOPE.mul(absROI).sub( ROI_PUNISH_NEG_BIAS ) ) ) .div(PRECISION); } else { // ROI greater than 25%, burn all stake return 0; } } } /** * @notice Handles and investment by doing the necessary trades using __kyberTrade() or Fulcrum trading * @param _investmentId the ID of the investment to be handled * @param _minPrice the minimum price for the trade * @param _maxPrice the maximum price for the trade * @param _buy whether to buy or sell the given investment * @param _calldata calldata for 1inch trading * @param _useKyber true for Kyber Network, false for 1inch */ function __handleInvestment( address _sender, uint256 _investmentId, uint256 _minPrice, uint256 _maxPrice, bool _buy, bytes memory _calldata, bool _useKyber ) internal returns (uint256 _actualDestAmount, uint256 _actualSrcAmount) { Investment storage investment = userInvestments[_sender][_investmentId]; address token = investment.tokenAddress; // Basic trading uint256 dInS; // price of dest token denominated in src token uint256 sInD; // price of src token denominated in dest token if (_buy) { if (_useKyber) { ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __kyberTrade( usdc, totalFundsInUSDC.mul(investment.stake).div( cToken.totalSupply() ), ERC20Detailed(token) ); } else { // 1inch trading ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __oneInchTrade( usdc, totalFundsInUSDC.mul(investment.stake).div( cToken.totalSupply() ), ERC20Detailed(token), _calldata ); } require(_minPrice <= dInS && dInS <= _maxPrice); investment.buyPrice = dInS; investment.tokenAmount = _actualDestAmount; investment.buyCostInUSDC = _actualSrcAmount; } else { if (_useKyber) { ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __kyberTrade( ERC20Detailed(token), investment.tokenAmount, usdc ); } else { ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __oneInchTrade( ERC20Detailed(token), investment.tokenAmount, usdc, _calldata ); } require(_minPrice <= sInD && sInD <= _maxPrice); investment.sellPrice = sInD; } } /** * @notice Separated from createCompoundOrder() to avoid stack too deep error */ function __createCompoundOrder( bool _orderType, // True for shorting, false for longing address _tokenAddress, uint256 _stake, uint256 _collateralAmountInUSDC ) internal returns (CompoundOrder) { CompoundOrderFactory factory = CompoundOrderFactory( compoundFactoryAddr ); uint256 loanAmountInUSDC = _collateralAmountInUSDC .mul(COLLATERAL_RATIO_MODIFIER) .div(PRECISION) .mul(factory.getMarketCollateralFactor(_tokenAddress)) .div(PRECISION); CompoundOrder order = factory.createOrder( _tokenAddress, cycleNumber, _stake, _collateralAmountInUSDC, loanAmountInUSDC, _orderType ); return order; } /** * @notice Returns stake to manager after investment is sold, including reward/penalty based on performance */ function __returnStake(uint256 _receiveRepTokenAmount, uint256 _stake) internal { require(cToken.destroyTokens(address(this), _stake)); require(cToken.generateTokens(msg.sender, _receiveRepTokenAmount)); } /** * @notice Records risk taken in a trade based on stake and time of investment */ function __recordRisk( address _sender, uint256 _stake, uint256 _buyTime ) internal { _riskTakenInCycle[_sender][cycleNumber] = riskTakenInCycle( _sender, cycleNumber ) .add(_stake.mul(now.sub(_buyTime))); } } pragma solidity ^0.5.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity 0.5.17; import "./PeakDeFiStorage.sol"; import "./derivatives/CompoundOrderFactory.sol"; import "@nomiclabs/buidler/console.sol"; /** * @title Part of the functions for PeakDeFiFund * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiLogic2 is PeakDeFiStorage, Utils(address(0), address(0), address(0)) { /** * @notice Passes if the fund has not finalized the next smart contract to upgrade to */ modifier notReadyForUpgrade { require(hasFinalizedNextVersion == false); _; } /** * @notice Executes function only during the given cycle phase. * @param phase the cycle phase during which the function may be called */ modifier during(CyclePhase phase) { require(cyclePhase == phase); if (cyclePhase == CyclePhase.Intermission) { require(isInitialized); } _; } /** * Deposit & Withdraw */ function depositEther(address _referrer) public payable { bytes memory nil; depositEtherAdvanced(true, nil, _referrer); } /** * @notice Deposit Ether into the fund. Ether will be converted into USDC. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading * @param _referrer the referrer's address */ function depositEtherAdvanced( bool _useKyber, bytes memory _calldata, address _referrer ) public payable nonReentrant notReadyForUpgrade { // Buy USDC with ETH uint256 actualUSDCDeposited; uint256 actualETHDeposited; if (_useKyber) { (, , actualUSDCDeposited, actualETHDeposited) = __kyberTrade( ETH_TOKEN_ADDRESS, msg.value, usdc ); } else { (, , actualUSDCDeposited, actualETHDeposited) = __oneInchTrade( ETH_TOKEN_ADDRESS, msg.value, usdc, _calldata ); } // Send back leftover ETH uint256 leftOverETH = msg.value.sub(actualETHDeposited); if (leftOverETH > 0) { msg.sender.transfer(leftOverETH); } // Register investment __deposit(actualUSDCDeposited, _referrer); // Emit event emit Deposit( cycleNumber, msg.sender, address(ETH_TOKEN_ADDRESS), actualETHDeposited, actualUSDCDeposited, now ); } /** * @notice Deposit USDC Stablecoin into the fund. * @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount. * @param _referrer the referrer's address */ function depositUSDC(uint256 _usdcAmount, address _referrer) public nonReentrant notReadyForUpgrade { usdc.safeTransferFrom(msg.sender, address(this), _usdcAmount); // Register investment __deposit(_usdcAmount, _referrer); // Emit event emit Deposit( cycleNumber, msg.sender, USDC_ADDR, _usdcAmount, _usdcAmount, now ); } function depositToken( address _tokenAddr, uint256 _tokenAmount, address _referrer ) public { bytes memory nil; depositTokenAdvanced(_tokenAddr, _tokenAmount, true, nil, _referrer); } /** * @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC. * @param _tokenAddr the address of the token to be deposited * @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading * @param _referrer the referrer's address */ function depositTokenAdvanced( address _tokenAddr, uint256 _tokenAmount, bool _useKyber, bytes memory _calldata, address _referrer ) public nonReentrant notReadyForUpgrade isValidToken(_tokenAddr) { require( _tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS) ); ERC20Detailed token = ERC20Detailed(_tokenAddr); token.safeTransferFrom(msg.sender, address(this), _tokenAmount); // Convert token into USDC uint256 actualUSDCDeposited; uint256 actualTokenDeposited; if (_useKyber) { (, , actualUSDCDeposited, actualTokenDeposited) = __kyberTrade( token, _tokenAmount, usdc ); } else { (, , actualUSDCDeposited, actualTokenDeposited) = __oneInchTrade( token, _tokenAmount, usdc, _calldata ); } // Give back leftover tokens uint256 leftOverTokens = _tokenAmount.sub(actualTokenDeposited); if (leftOverTokens > 0) { token.safeTransfer(msg.sender, leftOverTokens); } // Register investment __deposit(actualUSDCDeposited, _referrer); // Emit event emit Deposit( cycleNumber, msg.sender, _tokenAddr, actualTokenDeposited, actualUSDCDeposited, now ); } function withdrawEther(uint256 _amountInUSDC) external { bytes memory nil; withdrawEtherAdvanced(_amountInUSDC, true, nil); } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading */ function withdrawEtherAdvanced( uint256 _amountInUSDC, bool _useKyber, bytes memory _calldata ) public nonReentrant during(CyclePhase.Intermission) { // Buy ETH uint256 actualETHWithdrawn; uint256 actualUSDCWithdrawn; if (_useKyber) { (, , actualETHWithdrawn, actualUSDCWithdrawn) = __kyberTrade( usdc, _amountInUSDC, ETH_TOKEN_ADDRESS ); } else { (, , actualETHWithdrawn, actualUSDCWithdrawn) = __oneInchTrade( usdc, _amountInUSDC, ETH_TOKEN_ADDRESS, _calldata ); } __withdraw(actualUSDCWithdrawn); // Transfer Ether to user msg.sender.transfer(actualETHWithdrawn); // Emit event emit Withdraw( cycleNumber, msg.sender, address(ETH_TOKEN_ADDRESS), actualETHWithdrawn, actualUSDCWithdrawn, now ); } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawUSDC(uint256 _amountInUSDC) external nonReentrant during(CyclePhase.Intermission) { __withdraw(_amountInUSDC); // Transfer USDC to user usdc.safeTransfer(msg.sender, _amountInUSDC); // Emit event emit Withdraw( cycleNumber, msg.sender, USDC_ADDR, _amountInUSDC, _amountInUSDC, now ); } function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external { bytes memory nil; withdrawTokenAdvanced(_tokenAddr, _amountInUSDC, true, nil); } /** * @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network. * @param _tokenAddr the address of the token to be withdrawn into the caller's account * @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading */ function withdrawTokenAdvanced( address _tokenAddr, uint256 _amountInUSDC, bool _useKyber, bytes memory _calldata ) public during(CyclePhase.Intermission) nonReentrant isValidToken(_tokenAddr) { require( _tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS) ); ERC20Detailed token = ERC20Detailed(_tokenAddr); // Convert USDC into desired tokens uint256 actualTokenWithdrawn; uint256 actualUSDCWithdrawn; if (_useKyber) { (, , actualTokenWithdrawn, actualUSDCWithdrawn) = __kyberTrade( usdc, _amountInUSDC, token ); } else { (, , actualTokenWithdrawn, actualUSDCWithdrawn) = __oneInchTrade( usdc, _amountInUSDC, token, _calldata ); } __withdraw(actualUSDCWithdrawn); // Transfer tokens to user token.safeTransfer(msg.sender, actualTokenWithdrawn); // Emit event emit Withdraw( cycleNumber, msg.sender, _tokenAddr, actualTokenWithdrawn, actualUSDCWithdrawn, now ); } /** * Manager registration */ /** * @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithUSDC() public during(CyclePhase.Intermission) nonReentrant { require(!isPermissioned); require(managersOnboardedThisCycle < maxNewManagersPerCycle); managersOnboardedThisCycle = managersOnboardedThisCycle.add(1); uint256 peakStake = peakStaking.userStakeAmount(msg.sender); require(peakStake >= peakManagerStakeRequired); uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION); usdc.safeTransferFrom(msg.sender, address(this), donationInUSDC); __register(donationInUSDC); } /** * @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithETH() public payable during(CyclePhase.Intermission) nonReentrant { require(!isPermissioned); require(managersOnboardedThisCycle < maxNewManagersPerCycle); managersOnboardedThisCycle = managersOnboardedThisCycle.add(1); uint256 peakStake = peakStaking.userStakeAmount(msg.sender); require(peakStake >= peakManagerStakeRequired); uint256 receivedUSDC; // trade ETH for USDC (, , receivedUSDC, ) = __kyberTrade(ETH_TOKEN_ADDRESS, msg.value, usdc); // if USDC value is greater than the amount required, return excess USDC to msg.sender uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION); if (receivedUSDC > donationInUSDC) { usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC)); receivedUSDC = donationInUSDC; } // register new manager __register(receivedUSDC); } /** * @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. * @param _token the token to be used for payment * @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals */ function registerWithToken(address _token, uint256 _donationInTokens) public during(CyclePhase.Intermission) nonReentrant { require(!isPermissioned); require(managersOnboardedThisCycle < maxNewManagersPerCycle); managersOnboardedThisCycle = managersOnboardedThisCycle.add(1); uint256 peakStake = peakStaking.userStakeAmount(msg.sender); require(peakStake >= peakManagerStakeRequired); require( _token != address(0) && _token != address(ETH_TOKEN_ADDRESS) && _token != USDC_ADDR ); ERC20Detailed token = ERC20Detailed(_token); require(token.totalSupply() > 0); token.safeTransferFrom(msg.sender, address(this), _donationInTokens); uint256 receivedUSDC; (, , receivedUSDC, ) = __kyberTrade(token, _donationInTokens, usdc); // if USDC value is greater than the amount required, return excess USDC to msg.sender uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION); if (receivedUSDC > donationInUSDC) { usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC)); receivedUSDC = donationInUSDC; } // register new manager __register(receivedUSDC); } function peakAdminRegisterManager(address _manager, uint256 _reptokenAmount) public during(CyclePhase.Intermission) nonReentrant onlyOwner { require(isPermissioned); // mint REP for msg.sender require(cToken.generateTokens(_manager, _reptokenAmount)); // Set risk fallback base stake _baseRiskStakeFallback[_manager] = _baseRiskStakeFallback[_manager].add( _reptokenAmount ); // Set last active cycle for msg.sender to be the current cycle _lastActiveCycle[_manager] = cycleNumber; // emit events emit Register(_manager, 0, _reptokenAmount); } /** * @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _tokenAddr address of the token to be sold * @param _calldata the 1inch trade call data */ function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata) external during(CyclePhase.Intermission) nonReentrant isValidToken(_tokenAddr) { ERC20Detailed token = ERC20Detailed(_tokenAddr); (, , uint256 actualUSDCReceived, ) = __oneInchTrade( token, getBalance(token, address(this)), usdc, _calldata ); totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived); } /** * @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _orderAddress address of the CompoundOrder to be sold */ function sellLeftoverCompoundOrder(address payable _orderAddress) public during(CyclePhase.Intermission) nonReentrant { // Load order info require(_orderAddress != address(0)); CompoundOrder order = CompoundOrder(_orderAddress); require(order.isSold() == false && order.cycleNumber() < cycleNumber); // Sell short order // Not using outputAmount returned by order.sellOrder() because _orderAddress could point to a malicious contract uint256 beforeUSDCBalance = usdc.balanceOf(address(this)); order.sellOrder(0, MAX_QTY); uint256 actualUSDCReceived = usdc.balanceOf(address(this)).sub( beforeUSDCBalance ); totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived); } /** * @notice Registers `msg.sender` as a manager. * @param _donationInUSDC the amount of USDC to be used for registration */ function __register(uint256 _donationInUSDC) internal { require( cToken.balanceOf(msg.sender) == 0 && userInvestments[msg.sender].length == 0 && userCompoundOrders[msg.sender].length == 0 ); // each address can only join once // mint REP for msg.sender uint256 repAmount = _donationInUSDC.mul(PRECISION).div(reptokenPrice); require(cToken.generateTokens(msg.sender, repAmount)); // Set risk fallback base stake _baseRiskStakeFallback[msg.sender] = repAmount; // Set last active cycle for msg.sender to be the current cycle _lastActiveCycle[msg.sender] = cycleNumber; // keep USDC in the fund totalFundsInUSDC = totalFundsInUSDC.add(_donationInUSDC); // emit events emit Register(msg.sender, _donationInUSDC, repAmount); } /** * @notice Handles deposits by minting PeakDeFi Shares & updating total funds. * @param _depositUSDCAmount The amount of the deposit in USDC * @param _referrer The deposit referrer */ function __deposit(uint256 _depositUSDCAmount, address _referrer) internal { // Register investment and give shares uint256 shareAmount; if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) { uint256 usdcDecimals = getDecimals(usdc); shareAmount = _depositUSDCAmount.mul(PRECISION).div(10**usdcDecimals); } else { shareAmount = _depositUSDCAmount.mul(sToken.totalSupply()).div( totalFundsInUSDC ); } require(sToken.generateTokens(msg.sender, shareAmount)); totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount); totalFundsAtManagePhaseStart = totalFundsAtManagePhaseStart.add( _depositUSDCAmount ); // Handle peakReferralToken if (peakReward.canRefer(msg.sender, _referrer)) { peakReward.refer(msg.sender, _referrer); } address actualReferrer = peakReward.referrerOf(msg.sender); if (actualReferrer != address(0)) { require( peakReferralToken.generateTokens(actualReferrer, shareAmount) ); } } /** * @notice Handles deposits by burning PeakDeFi Shares & updating total funds. * @param _withdrawUSDCAmount The amount of the withdrawal in USDC */ function __withdraw(uint256 _withdrawUSDCAmount) internal { // Burn Shares uint256 shareAmount = _withdrawUSDCAmount.mul(sToken.totalSupply()).div( totalFundsInUSDC ); require(sToken.destroyTokens(msg.sender, shareAmount)); totalFundsInUSDC = totalFundsInUSDC.sub(_withdrawUSDCAmount); // Handle peakReferralToken address actualReferrer = peakReward.referrerOf(msg.sender); if (actualReferrer != address(0)) { uint256 balance = peakReferralToken.balanceOf(actualReferrer); uint256 burnReferralTokenAmount = shareAmount > balance ? balance : shareAmount; require( peakReferralToken.destroyTokens( actualReferrer, burnReferralTokenAmount ) ); } } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.8.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 logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", 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)); } } pragma solidity 0.5.17; import "./PeakDeFiStorage.sol"; contract PeakDeFiLogic3 is PeakDeFiStorage, Utils(address(0), address(0), address(0)) { /** * @notice Passes if the fund has not finalized the next smart contract to upgrade to */ modifier notReadyForUpgrade { require(hasFinalizedNextVersion == false); _; } /** * @notice Executes function only during the given cycle phase. * @param phase the cycle phase during which the function may be called */ modifier during(CyclePhase phase) { require(cyclePhase == phase); if (cyclePhase == CyclePhase.Intermission) { require(isInitialized); } _; } /** * Next phase transition handler * @notice Moves the fund to the next phase in the investment cycle. */ function nextPhase() public nonReentrant { require( now >= startTimeOfCyclePhase.add(phaseLengths[uint256(cyclePhase)]) ); if (isInitialized == false) { // first cycle of this smart contract deployment // check whether ready for starting cycle isInitialized = true; require(proxyAddr != address(0)); // has initialized proxy require(proxy.peakdefiFundAddress() == address(this)); // upgrade complete require(hasInitializedTokenListings); // has initialized token listings // execute initialization function __init(); require( previousVersion == address(0) || (previousVersion != address(0) && getBalance(usdc, address(this)) > 0) ); // has transfered assets from previous version } else { // normal phase changing if (cyclePhase == CyclePhase.Intermission) { require(hasFinalizedNextVersion == false); // Shouldn't progress to next phase if upgrading // Update total funds at management phase's beginning totalFundsAtManagePhaseStart = totalFundsInUSDC; // reset number of managers onboarded managersOnboardedThisCycle = 0; } else if (cyclePhase == CyclePhase.Manage) { // Burn any RepToken left in PeakDeFiFund's account require( cToken.destroyTokens( address(this), cToken.balanceOf(address(this)) ) ); // Pay out commissions and fees uint256 profit = 0; uint256 usdcBalanceAtManagePhaseStart = totalFundsAtManagePhaseStart.add(totalCommissionLeft); if ( getBalance(usdc, address(this)) > usdcBalanceAtManagePhaseStart ) { profit = getBalance(usdc, address(this)).sub( usdcBalanceAtManagePhaseStart ); } totalFundsInUSDC = getBalance(usdc, address(this)) .sub(totalCommissionLeft) .sub(peakReferralTotalCommissionLeft); // Calculate manager commissions uint256 commissionThisCycle = COMMISSION_RATE .mul(profit) .add(ASSET_FEE_RATE.mul(totalFundsInUSDC)) .div(PRECISION); _totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle( cycleNumber ) .add(commissionThisCycle); // account for penalties totalCommissionLeft = totalCommissionLeft.add( commissionThisCycle ); // Calculate referrer commissions uint256 peakReferralCommissionThisCycle = PEAK_COMMISSION_RATE .mul(profit) .mul(peakReferralToken.totalSupply()) .div(sToken.totalSupply()) .div(PRECISION); _peakReferralTotalCommissionOfCycle[cycleNumber] = peakReferralTotalCommissionOfCycle( cycleNumber ) .add(peakReferralCommissionThisCycle); peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft .add(peakReferralCommissionThisCycle); totalFundsInUSDC = getBalance(usdc, address(this)) .sub(totalCommissionLeft) .sub(peakReferralTotalCommissionLeft); // Give the developer PeakDeFi shares inflation funding uint256 devFunding = devFundingRate .mul(sToken.totalSupply()) .div(PRECISION); require(sToken.generateTokens(devFundingAccount, devFunding)); // Emit event emit TotalCommissionPaid( cycleNumber, totalCommissionOfCycle(cycleNumber) ); emit PeakReferralTotalCommissionPaid( cycleNumber, peakReferralTotalCommissionOfCycle(cycleNumber) ); _managePhaseEndBlock[cycleNumber] = block.number; // Clear/update upgrade related data if (nextVersion == address(this)) { // The developer proposed a candidate, but the managers decide to not upgrade at all // Reset upgrade process delete nextVersion; delete hasFinalizedNextVersion; } if (nextVersion != address(0)) { hasFinalizedNextVersion = true; emit FinalizedNextVersion(cycleNumber, nextVersion); } // Start new cycle cycleNumber = cycleNumber.add(1); } cyclePhase = CyclePhase(addmod(uint256(cyclePhase), 1, 2)); } startTimeOfCyclePhase = now; // Reward caller if they're a manager if (cToken.balanceOf(msg.sender) > 0) { require(cToken.generateTokens(msg.sender, NEXT_PHASE_REWARD)); } emit ChangedPhase( cycleNumber, uint256(cyclePhase), now, totalFundsInUSDC ); } /** * @notice Initializes several important variables after smart contract upgrade */ function __init() internal { _managePhaseEndBlock[cycleNumber.sub(1)] = block.number; // load values from previous version totalCommissionLeft = previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).totalCommissionLeft(); totalFundsInUSDC = getBalance(usdc, address(this)).sub( totalCommissionLeft ); } /** * Upgrading functions */ /** * @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to. * The developer may change the candidate during the Intermission phase. * @param _candidate the address of the candidate smart contract * @return True if successfully changed candidate, false otherwise. */ function developerInitiateUpgrade(address payable _candidate) public onlyOwner notReadyForUpgrade during(CyclePhase.Intermission) nonReentrant returns (bool _success) { if (_candidate == address(0) || _candidate == address(this)) { return false; } nextVersion = _candidate; emit DeveloperInitiatedUpgrade(cycleNumber, _candidate); return true; } /** Commission functions */ /** * @notice Returns the commission balance of `_manager` * @return the commission balance and the received penalty, denoted in USDC */ function commissionBalanceOf(address _manager) public view returns (uint256 _commission, uint256 _penalty) { if (lastCommissionRedemption(_manager) >= cycleNumber) { return (0, 0); } uint256 cycle = lastCommissionRedemption(_manager) > 0 ? lastCommissionRedemption(_manager) : 1; uint256 cycleCommission; uint256 cyclePenalty; for (; cycle < cycleNumber; cycle++) { (cycleCommission, cyclePenalty) = commissionOfAt(_manager, cycle); _commission = _commission.add(cycleCommission); _penalty = _penalty.add(cyclePenalty); } } /** * @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle * @return the commission amount and the received penalty, denoted in USDC */ function commissionOfAt(address _manager, uint256 _cycle) public view returns (uint256 _commission, uint256 _penalty) { if (hasRedeemedCommissionForCycle(_manager, _cycle)) { return (0, 0); } // take risk into account uint256 baseRepTokenBalance = cToken.balanceOfAt( _manager, managePhaseEndBlock(_cycle.sub(1)) ); uint256 baseStake = baseRepTokenBalance == 0 ? baseRiskStakeFallback(_manager) : baseRepTokenBalance; if (baseRepTokenBalance == 0 && baseRiskStakeFallback(_manager) == 0) { return (0, 0); } uint256 riskTakenProportion = riskTakenInCycle(_manager, _cycle) .mul(PRECISION) .div(baseStake.mul(MIN_RISK_TIME)); // risk / threshold riskTakenProportion = riskTakenProportion > PRECISION ? PRECISION : riskTakenProportion; // max proportion is 1 uint256 fullCommission = totalCommissionOfCycle(_cycle) .mul(cToken.balanceOfAt(_manager, managePhaseEndBlock(_cycle))) .div(cToken.totalSupplyAt(managePhaseEndBlock(_cycle))); _commission = fullCommission.mul(riskTakenProportion).div(PRECISION); _penalty = fullCommission.sub(_commission); } /** * @notice Redeems commission. */ function redeemCommission(bool _inShares) public during(CyclePhase.Intermission) nonReentrant { uint256 commission = __redeemCommission(); if (_inShares) { // Deposit commission into fund __deposit(commission); // Emit deposit event emit Deposit( cycleNumber, msg.sender, USDC_ADDR, commission, commission, now ); } else { // Transfer the commission in USDC usdc.safeTransfer(msg.sender, commission); } } /** * @notice Redeems commission for a particular cycle. * @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function redeemCommissionForCycle(bool _inShares, uint256 _cycle) public during(CyclePhase.Intermission) nonReentrant { require(_cycle < cycleNumber); uint256 commission = __redeemCommissionForCycle(_cycle); if (_inShares) { // Deposit commission into fund __deposit(commission); // Emit deposit event emit Deposit( cycleNumber, msg.sender, USDC_ADDR, commission, commission, now ); } else { // Transfer the commission in USDC usdc.safeTransfer(msg.sender, commission); } } /** * @notice Redeems the commission for all previous cycles. Updates the related variables. * @return the amount of commission to be redeemed */ function __redeemCommission() internal returns (uint256 _commission) { require(lastCommissionRedemption(msg.sender) < cycleNumber); uint256 penalty; // penalty received for not taking enough risk (_commission, penalty) = commissionBalanceOf(msg.sender); // record the redemption to prevent double-redemption for ( uint256 i = lastCommissionRedemption(msg.sender); i < cycleNumber; i++ ) { _hasRedeemedCommissionForCycle[msg.sender][i] = true; } _lastCommissionRedemption[msg.sender] = cycleNumber; // record the decrease in commission pool totalCommissionLeft = totalCommissionLeft.sub(_commission); // include commission penalty to this cycle's total commission pool _totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle( cycleNumber ) .add(penalty); // clear investment arrays to save space delete userInvestments[msg.sender]; delete userCompoundOrders[msg.sender]; emit CommissionPaid(cycleNumber, msg.sender, _commission); } /** * @notice Redeems commission for a particular cycle. Updates the related variables. * @param _cycle the cycle for which the commission will be redeemed * @return the amount of commission to be redeemed */ function __redeemCommissionForCycle(uint256 _cycle) internal returns (uint256 _commission) { require(!hasRedeemedCommissionForCycle(msg.sender, _cycle)); uint256 penalty; // penalty received for not taking enough risk (_commission, penalty) = commissionOfAt(msg.sender, _cycle); _hasRedeemedCommissionForCycle[msg.sender][_cycle] = true; // record the decrease in commission pool totalCommissionLeft = totalCommissionLeft.sub(_commission); // include commission penalty to this cycle's total commission pool _totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle( cycleNumber ) .add(penalty); // clear investment arrays to save space delete userInvestments[msg.sender]; delete userCompoundOrders[msg.sender]; emit CommissionPaid(_cycle, msg.sender, _commission); } /** * @notice Handles deposits by minting PeakDeFi Shares & updating total funds. * @param _depositUSDCAmount The amount of the deposit in USDC */ function __deposit(uint256 _depositUSDCAmount) internal { // Register investment and give shares if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) { require(sToken.generateTokens(msg.sender, _depositUSDCAmount)); } else { require( sToken.generateTokens( msg.sender, _depositUSDCAmount.mul(sToken.totalSupply()).div( totalFundsInUSDC ) ) ); } totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount); } /** PeakDeFi */ /** * @notice Returns the commission balance of `_referrer` * @return the commission balance, denoted in USDC */ function peakReferralCommissionBalanceOf(address _referrer) public view returns (uint256 _commission) { if (peakReferralLastCommissionRedemption(_referrer) >= cycleNumber) { return (0); } uint256 cycle = peakReferralLastCommissionRedemption(_referrer) > 0 ? peakReferralLastCommissionRedemption(_referrer) : 1; uint256 cycleCommission; for (; cycle < cycleNumber; cycle++) { (cycleCommission) = peakReferralCommissionOfAt(_referrer, cycle); _commission = _commission.add(cycleCommission); } } /** * @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle * @return the commission amount, denoted in USDC */ function peakReferralCommissionOfAt(address _referrer, uint256 _cycle) public view returns (uint256 _commission) { _commission = peakReferralTotalCommissionOfCycle(_cycle) .mul( peakReferralToken.balanceOfAt( _referrer, managePhaseEndBlock(_cycle) ) ) .div(peakReferralToken.totalSupplyAt(managePhaseEndBlock(_cycle))); } /** * @notice Redeems commission. */ function peakReferralRedeemCommission() public during(CyclePhase.Intermission) nonReentrant { uint256 commission = __peakReferralRedeemCommission(); // Transfer the commission in USDC usdc.safeApprove(address(peakReward), commission); peakReward.payCommission(msg.sender, address(usdc), commission, false); } /** * @notice Redeems commission for a particular cycle. * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function peakReferralRedeemCommissionForCycle(uint256 _cycle) public during(CyclePhase.Intermission) nonReentrant { require(_cycle < cycleNumber); uint256 commission = __peakReferralRedeemCommissionForCycle(_cycle); // Transfer the commission in USDC usdc.safeApprove(address(peakReward), commission); peakReward.payCommission(msg.sender, address(usdc), commission, false); } /** * @notice Redeems the commission for all previous cycles. Updates the related variables. * @return the amount of commission to be redeemed */ function __peakReferralRedeemCommission() internal returns (uint256 _commission) { require(peakReferralLastCommissionRedemption(msg.sender) < cycleNumber); _commission = peakReferralCommissionBalanceOf(msg.sender); // record the redemption to prevent double-redemption for ( uint256 i = peakReferralLastCommissionRedemption(msg.sender); i < cycleNumber; i++ ) { _peakReferralHasRedeemedCommissionForCycle[msg.sender][i] = true; } _peakReferralLastCommissionRedemption[msg.sender] = cycleNumber; // record the decrease in commission pool peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub( _commission ); emit PeakReferralCommissionPaid(cycleNumber, msg.sender, _commission); } /** * @notice Redeems commission for a particular cycle. Updates the related variables. * @param _cycle the cycle for which the commission will be redeemed * @return the amount of commission to be redeemed */ function __peakReferralRedeemCommissionForCycle(uint256 _cycle) internal returns (uint256 _commission) { require(!peakReferralHasRedeemedCommissionForCycle(msg.sender, _cycle)); _commission = peakReferralCommissionOfAt(msg.sender, _cycle); _peakReferralHasRedeemedCommissionForCycle[msg.sender][_cycle] = true; // record the decrease in commission pool peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub( _commission ); emit PeakReferralCommissionPaid(_cycle, msg.sender, _commission); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "../interfaces/CERC20.sol"; import "../interfaces/Comptroller.sol"; contract TestCERC20 is CERC20 { using SafeMath for uint; uint public constant PRECISION = 10 ** 18; uint public constant MAX_UINT = 2 ** 256 - 1; address public _underlying; uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION; mapping(address => uint) public _balanceOf; mapping(address => uint) public _borrowBalanceCurrent; Comptroller public COMPTROLLER; constructor(address __underlying, address _comptrollerAddr) public { _underlying = __underlying; COMPTROLLER = Comptroller(_comptrollerAddr); } function mint(uint mintAmount) external returns (uint) { ERC20Detailed token = ERC20Detailed(_underlying); require(token.transferFrom(msg.sender, address(this), mintAmount)); _balanceOf[msg.sender] = _balanceOf[msg.sender].add(mintAmount.mul(10 ** this.decimals()).div(PRECISION)); return 0; } function redeemUnderlying(uint redeemAmount) external returns (uint) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION)); ERC20Detailed token = ERC20Detailed(_underlying); require(token.transfer(msg.sender, redeemAmount)); return 0; } function borrow(uint amount) external returns (uint) { // add to borrow balance _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount); // transfer asset ERC20Detailed token = ERC20Detailed(_underlying); require(token.transfer(msg.sender, amount)); return 0; } function repayBorrow(uint amount) external returns (uint) { // accept repayment ERC20Detailed token = ERC20Detailed(_underlying); uint256 repayAmount = amount == MAX_UINT ? _borrowBalanceCurrent[msg.sender] : amount; require(token.transferFrom(msg.sender, address(this), repayAmount)); // subtract from borrow balance _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(repayAmount); return 0; } function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; } function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; } function underlying() external view returns (address) { return _underlying; } function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; } function decimals() external view returns (uint) { return 8; } } pragma solidity 0.5.17; import "./TestCERC20.sol"; contract TestCERC20Factory { mapping(address => address) public createdTokens; event CreatedToken(address underlying, address cToken); function newToken(address underlying, address comptroller) public returns(address) { require(createdTokens[underlying] == address(0)); TestCERC20 token = new TestCERC20(underlying, comptroller); createdTokens[underlying] = address(token); emit CreatedToken(underlying, address(token)); return address(token); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/CEther.sol"; import "../interfaces/Comptroller.sol"; contract TestCEther is CEther { using SafeMath for uint; uint public constant PRECISION = 10 ** 18; uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION; mapping(address => uint) public _balanceOf; mapping(address => uint) public _borrowBalanceCurrent; Comptroller public COMPTROLLER; constructor(address _comptrollerAddr) public { COMPTROLLER = Comptroller(_comptrollerAddr); } function mint() external payable { _balanceOf[msg.sender] = _balanceOf[msg.sender].add(msg.value.mul(10 ** this.decimals()).div(PRECISION)); } function redeemUnderlying(uint redeemAmount) external returns (uint) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION)); msg.sender.transfer(redeemAmount); return 0; } function borrow(uint amount) external returns (uint) { // add to borrow balance _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount); // transfer asset msg.sender.transfer(amount); return 0; } function repayBorrow() external payable { _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(msg.value); } function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; } function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; } function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; } function decimals() external view returns (uint) { return 8; } function() external payable {} } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/Comptroller.sol"; import "../interfaces/PriceOracle.sol"; import "../interfaces/CERC20.sol"; contract TestComptroller is Comptroller { using SafeMath for uint; uint256 internal constant PRECISION = 10 ** 18; mapping(address => address[]) public getAssetsIn; uint256 internal collateralFactor = 2 * PRECISION / 3; constructor() public {} function enterMarkets(address[] calldata cTokens) external returns (uint[] memory) { uint[] memory errors = new uint[](cTokens.length); for (uint256 i = 0; i < cTokens.length; i = i.add(1)) { getAssetsIn[msg.sender].push(cTokens[i]); errors[i] = 0; } return errors; } function markets(address /*cToken*/) external view returns (bool isListed, uint256 collateralFactorMantissa) { return (true, collateralFactor); } } pragma solidity 0.5.17; import "../interfaces/KyberNetwork.sol"; import "../Utils.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; contract TestKyberNetwork is KyberNetwork, Utils(address(0), address(0), address(0)), Ownable { mapping(address => uint256) public priceInUSDC; constructor(address[] memory _tokens, uint256[] memory _pricesInUSDC) public { for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { priceInUSDC[_tokens[i]] = _pricesInUSDC[i]; } } function setTokenPrice(address _token, uint256 _priceInUSDC) public onlyOwner { priceInUSDC[_token] = _priceInUSDC; } function setAllTokenPrices(address[] memory _tokens, uint256[] memory _pricesInUSDC) public onlyOwner { for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { priceInUSDC[_tokens[i]] = _pricesInUSDC[i]; } } function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint /*srcQty*/) external view returns (uint expectedRate, uint slippageRate) { uint256 result = priceInUSDC[address(src)].mul(10**getDecimals(dest)).mul(PRECISION).div(priceInUSDC[address(dest)].mul(10**getDecimals(src))); return (result, result); } function tradeWithHint( ERC20Detailed src, uint srcAmount, ERC20Detailed dest, address payable destAddress, uint maxDestAmount, uint /*minConversionRate*/, address /*walletId*/, bytes calldata /*hint*/ ) external payable returns(uint) { require(calcDestAmount(src, srcAmount, dest) <= maxDestAmount); if (address(src) == address(ETH_TOKEN_ADDRESS)) { require(srcAmount == msg.value); } else { require(src.transferFrom(msg.sender, address(this), srcAmount)); } if (address(dest) == address(ETH_TOKEN_ADDRESS)) { destAddress.transfer(calcDestAmount(src, srcAmount, dest)); } else { require(dest.transfer(destAddress, calcDestAmount(src, srcAmount, dest))); } return calcDestAmount(src, srcAmount, dest); } function calcDestAmount( ERC20Detailed src, uint srcAmount, ERC20Detailed dest ) internal view returns (uint destAmount) { return srcAmount.mul(priceInUSDC[address(src)]).mul(10**getDecimals(dest)).div(priceInUSDC[address(dest)].mul(10**getDecimals(src))); } function() external payable {} } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "../interfaces/PriceOracle.sol"; import "../interfaces/CERC20.sol"; contract TestPriceOracle is PriceOracle, Ownable { using SafeMath for uint; uint public constant PRECISION = 10 ** 18; address public CETH_ADDR; mapping(address => uint256) public priceInUSD; constructor(address[] memory _tokens, uint256[] memory _pricesInUSD, address _cETH) public { for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { priceInUSD[_tokens[i]] = _pricesInUSD[i]; } CETH_ADDR = _cETH; } function setTokenPrice(address _token, uint256 _priceInUSD) public onlyOwner { priceInUSD[_token] = _priceInUSD; } function getUnderlyingPrice(address _cToken) external view returns (uint) { if (_cToken == CETH_ADDR) { return priceInUSD[_cToken]; } CERC20 cToken = CERC20(_cToken); ERC20Detailed underlying = ERC20Detailed(cToken.underlying()); return priceInUSD[_cToken].mul(PRECISION).div(10 ** uint256(underlying.decimals())); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; /** * @title An ERC20 token used for testing. * @author Zefram Lou (Zebang Liu) */ contract TestToken is ERC20Mintable, ERC20Burnable, ERC20Detailed { constructor(string memory name, string memory symbol, uint8 decimals) public ERC20Detailed(name, symbol, decimals) {} } pragma solidity 0.5.17; import "./TestToken.sol"; contract TestTokenFactory { mapping(bytes32 => address) public createdTokens; event CreatedToken(string symbol, address addr); function newToken(string memory name, string memory symbol, uint8 decimals) public returns(address) { bytes32 symbolHash = keccak256(abi.encodePacked(symbol)); require(createdTokens[symbolHash] == address(0)); TestToken token = new TestToken(name, symbol, decimals); token.addMinter(msg.sender); token.renounceMinter(); createdTokens[symbolHash] = address(token); emit CreatedToken(symbol, address(token)); return address(token); } function getToken(string memory symbol) public view returns(address) { return createdTokens[keccak256(abi.encodePacked(symbol))]; } } pragma solidity 0.5.17; contract TestUniswapOracle { function update() external returns (bool success) { return true; } function consult(address token, uint256 amountIn) external view returns (uint256 amountOut) { return 3 * 10**5; // 1 PEAK = 0.30 USDC } }
Convert a USDC amount to the amount of a given token that's of equal value
function __usdcToToken(address _cToken, uint256 _usdcAmount) internal view returns (uint256) { ERC20Detailed t = __underlyingToken(_cToken); return _usdcAmount.mul(PRECISION).div(10 ** getDecimals(usdc)).mul(10 ** getDecimals(t)).div(ORACLE.getUnderlyingPrice(_cToken).mul(10 ** getDecimals(t)).div(PRECISION)); }
15,851,461
./full_match/80001/0xd214185AA42cC815484Ff2552d1A7A89eB7E0e28/sources/Utility/Manager.sol
SECURITY: anyone can register. change to OrgAdmin only
function registerUser(address _newUser, string calldata _name) isOrgAdmin external {
5,572,830
./full_match/1/0x48deE19C0e44c147934702c12dc98963CA831009/sources/src/Asset/ERC1155ERC721.sol
Mint a token type for `creator` on slot `packId`. creator address of the creator of the token. packId unique packId for that token. hash hash of an IPFS cidv1 folder that contains the metadata of the token type in the file 0.json. supply number of tokens minted for that token type. rarity rarity power of the token. owner address that will receive the tokens. data extra data to accompany the minting call. return the id of the newly minted token type.
function mint( address creator, uint40 packId, bytes32 hash, uint256 supply, uint8 rarity, address owner, bytes calldata data ) external returns (uint256 id) { require(hash != 0, "hash is zero"); require(_bouncers[msg.sender], "only bouncer allowed to mint"); require(owner != address(0), "destination is zero address"); id = generateTokenId(creator, supply, packId, supply == 1 ? 0 : 1, 0); _mint( hash, supply, rarity, msg.sender, owner, id, data, false ); }
4,919,186
// File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: contracts/interfaces/IVat.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the vat contract from MakerDAO /// Taken from https://github.com/makerdao/developerguides/blob/master/devtools/working-with-dsproxy/working-with-dsproxy.md interface IVat { // function can(address, address) external view returns (uint); function hope(address) external; function nope(address) external; function live() external view returns (uint); function ilks(bytes32) external view returns (uint, uint, uint, uint, uint); function urns(bytes32, address) external view returns (uint, uint); function gem(bytes32, address) external view returns (uint); // function dai(address) external view returns (uint); function frob(bytes32, address, address, address, int, int) external; function fork(bytes32, address, address, int, int) external; function move(address, address, uint) external; function flux(bytes32, address, address, uint) external; } // File: contracts/interfaces/IPot.sol pragma solidity ^0.6.10; /// @dev interface for the pot contract from MakerDao /// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol interface IPot { function chi() external view returns (uint256); function pie(address) external view returns (uint256); // Not a function, but a public variable. function rho() external returns (uint256); function drip() external returns (uint256); function join(uint256) external; function exit(uint256) external; } // File: @openzeppelin/contracts/token/ERC20/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: contracts/interfaces/IWeth.sol pragma solidity ^0.6.10; interface IWeth { function deposit() external payable; function withdraw(uint) external; function approve(address, uint) external returns (bool) ; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); } // File: contracts/interfaces/IGemJoin.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the `Join.sol` contract from MakerDAO using ERC20 interface IGemJoin { function rely(address usr) external; function deny(address usr) external; function cage() external; function join(address usr, uint WAD) external; function exit(address usr, uint WAD) external; } // File: contracts/interfaces/IDaiJoin.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the `Join.sol` contract from MakerDAO using Dai interface IDaiJoin { function rely(address usr) external; function deny(address usr) external; function cage() external; function join(address usr, uint WAD) external; function exit(address usr, uint WAD) external; } // File: contracts/interfaces/IChai.sol pragma solidity ^0.6.10; /// @dev interface for the chai contract /// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol interface IChai { function balanceOf(address account) external view returns (uint256); function transfer(address dst, uint wad) external returns (bool); function move(address src, address dst, uint wad) external returns (bool); function transferFrom(address src, address dst, uint wad) external returns (bool); function approve(address usr, uint wad) external returns (bool); function dai(address usr) external returns (uint wad); function join(address dst, uint wad) external; function exit(address src, uint wad) external; function draw(address src, uint wad) external; function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function nonces(address account) external view returns (uint256); } // File: contracts/interfaces/ITreasury.sol pragma solidity ^0.6.10; interface ITreasury { function debt() external view returns(uint256); function savings() external view returns(uint256); function pushDai(address user, uint256 dai) external; function pullDai(address user, uint256 dai) external; function pushChai(address user, uint256 chai) external; function pullChai(address user, uint256 chai) external; function pushWeth(address to, uint256 weth) external; function pullWeth(address to, uint256 weth) external; function shutdown() external; function live() external view returns(bool); function vat() external view returns (IVat); function weth() external view returns (IWeth); function dai() external view returns (IERC20); function daiJoin() external view returns (IDaiJoin); function wethJoin() external view returns (IGemJoin); function pot() external view returns (IPot); function chai() external view returns (IChai); } // File: contracts/interfaces/IERC2612.sol // Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/ pragma solidity ^0.6.0; /** * @dev Interface of the ERC2612 standard as defined in the EIP. * * Adds the {permit} method, which can be used to change one's * {IERC20-allowance} without having to send a transaction, by signing a * message. This allows users to spend tokens without having to hold Ether. * * See https://eips.ethereum.org/EIPS/eip-2612. */ interface IERC2612 { /** * @dev Sets `amount` 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: * * - `owner` cannot be the zero address. * - `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 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current ERC2612 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); } // File: contracts/interfaces/IFYDai.sol pragma solidity ^0.6.10; interface IFYDai is IERC20, IERC2612 { function isMature() external view returns(bool); function maturity() external view returns(uint); function chi0() external view returns(uint); function rate0() external view returns(uint); function chiGrowth() external view returns(uint); function rateGrowth() external view returns(uint); function mature() external; function unlocked() external view returns (uint); function mint(address, uint) external; function burn(address, uint) external; function flashMint(uint, bytes calldata) external; function redeem(address, address, uint256) external returns (uint256); // 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/IFlashMinter.sol pragma solidity ^0.6.10; interface IFlashMinter { function executeOnFlashMint(uint256 fyDaiAmount, bytes calldata data) external; } // File: contracts/interfaces/IDelegable.sol pragma solidity ^0.6.10; interface IDelegable { function addDelegate(address) external; function addDelegateBySignature(address, address, uint, uint8, bytes32, bytes32) external; } // File: contracts/helpers/Delegable.sol pragma solidity ^0.6.10; /// @dev Delegable enables users to delegate their account management to other users. /// Delegable implements addDelegateBySignature, to add delegates using a signature instead of a separate transaction. contract Delegable is IDelegable { event Delegate(address indexed user, address indexed delegate, bool enabled); // keccak256("Signature(address user,address delegate,uint256 nonce,uint256 deadline)"); bytes32 public immutable SIGNATURE_TYPEHASH = 0x0d077601844dd17f704bafff948229d27f33b57445915754dfe3d095fda2beb7; bytes32 public immutable DELEGABLE_DOMAIN; mapping(address => uint) public signatureCount; mapping(address => mapping(address => bool)) public delegated; constructor () public { uint256 chainId; assembly { chainId := chainid() } DELEGABLE_DOMAIN = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes('Yield')), keccak256(bytes('1')), chainId, address(this) ) ); } /// @dev Require that msg.sender is the account holder or a delegate modifier onlyHolderOrDelegate(address holder, string memory errorMessage) { require( msg.sender == holder || delegated[holder][msg.sender], errorMessage ); _; } /// @dev Enable a delegate to act on the behalf of caller function addDelegate(address delegate) public override { _addDelegate(msg.sender, delegate); } /// @dev Stop a delegate from acting on the behalf of caller function revokeDelegate(address delegate) public { _revokeDelegate(msg.sender, delegate); } /// @dev Add a delegate through an encoded signature function addDelegateBySignature(address user, address delegate, uint deadline, uint8 v, bytes32 r, bytes32 s) public override { require(deadline >= block.timestamp, 'Delegable: Signature expired'); bytes32 hashStruct = keccak256( abi.encode( SIGNATURE_TYPEHASH, user, delegate, signatureCount[user]++, deadline ) ); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DELEGABLE_DOMAIN, hashStruct ) ); address signer = ecrecover(digest, v, r, s); require( signer != address(0) && signer == user, 'Delegable: Invalid signature' ); _addDelegate(user, delegate); } /// @dev Enable a delegate to act on the behalf of an user function _addDelegate(address user, address delegate) internal { require(!delegated[user][delegate], "Delegable: Already delegated"); delegated[user][delegate] = true; emit Delegate(user, delegate, true); } /// @dev Stop a delegate from acting on the behalf of an user function _revokeDelegate(address user, address delegate) internal { require(delegated[user][delegate], "Delegable: Already undelegated"); delegated[user][delegate] = false; emit Delegate(user, delegate, false); } } // File: @openzeppelin/contracts/math/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: contracts/helpers/DecimalMath.sol pragma solidity ^0.6.10; /// @dev Implements simple fixed point math mul and div operations for 27 decimals. contract DecimalMath { using SafeMath for uint256; uint256 constant public UNIT = 1e27; /// @dev Multiplies x and y, assuming they are both fixed point with 27 digits. function muld(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(y).div(UNIT); } /// @dev Divides x between y, assuming they are both fixed point with 27 digits. function divd(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(UNIT).div(y); } /// @dev Multiplies x and y, rounding up to the closest representable number. /// Assumes x and y are both fixed point with `decimals` digits. function muldrup(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x.mul(y); return z.mod(UNIT) == 0 ? z.div(UNIT) : z.div(UNIT).add(1); } /// @dev Divides x between y, rounding up to the closest representable number. /// Assumes x and y are both fixed point with `decimals` digits. function divdrup(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x.mul(UNIT); return z.mod(y) == 0 ? z.div(y) : z.div(y).add(1); } } // File: @openzeppelin/contracts/GSN/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. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @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: contracts/helpers/Orchestrated.sol pragma solidity ^0.6.10; /** * @dev Orchestrated allows to define static access control between multiple contracts. * This contract would be used as a parent contract of any contract that needs to restrict access to some methods, * which would be marked with the `onlyOrchestrated` modifier. * During deployment, the contract deployer (`owner`) can register any contracts that have privileged access by calling `orchestrate`. * Once deployment is completed, `owner` should call `transferOwnership(address(0))` to avoid any more contracts ever gaining privileged access. */ contract Orchestrated is Ownable { event GrantedAccess(address access, bytes4 signature); mapping(address => mapping (bytes4 => bool)) public orchestration; constructor () public Ownable() {} /// @dev Restrict usage to authorized users /// @param err The error to display if the validation fails modifier onlyOrchestrated(string memory err) { require(orchestration[msg.sender][msg.sig], err); _; } /// @dev Add orchestration /// @param user Address of user or contract having access to this contract. /// @param signature bytes4 signature of the function we are giving orchestrated access to. /// It seems to me a bad idea to give access to humans, and would use this only for predictable smart contracts. function orchestrate(address user, bytes4 signature) public onlyOwner { orchestration[user][signature] = true; emit GrantedAccess(user, signature); } /// @dev Adds orchestration for the provided function signatures function batchOrchestrate(address user, bytes4[] memory signatures) public onlyOwner { for (uint256 i = 0; i < signatures.length; i++) { orchestrate(user, signatures[i]); } } } // File: @openzeppelin/contracts/utils/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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/helpers/ERC20Permit.sol // Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/53516bc555a454862470e7860a9b5254db4d00f5/contracts/token/ERC20/ERC20Permit.sol pragma solidity ^0.6.0; /** * @dev Extension of {ERC20} that allows token holders to use their tokens * without sending any transactions by setting {IERC20-allowance} with a * signature using the {permit} method, and then spend them via * {IERC20-transferFrom}. * * The {permit} signature mechanism conforms to the {IERC2612} interface. */ abstract contract ERC20Permit is ERC20, IERC2612 { mapping (address => uint256) public override nonces; bytes32 public immutable PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public immutable DOMAIN_SEPARATOR; constructor(string memory name_, string memory symbol_) internal ERC20(name_, symbol_) { uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name_)), keccak256(bytes("1")), chainId, address(this) ) ); } /** * @dev See {IERC2612-permit}. * * In cases where the free option is not a concern, deadline can simply be * set to uint(-1), so it should be seen as an optional parameter */ function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { require(deadline >= block.timestamp, "ERC20Permit: expired deadline"); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, amount, 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, "ERC20Permit: invalid signature" ); _approve(owner, spender, amount); } } // File: contracts/FYDai.sol pragma solidity ^0.6.10; /** * @dev fyDai is an fyToken targeting Chai. * Each fyDai contract has a specific maturity time. One fyDai is worth one Chai at or after maturity time. * At maturity, the fyDai can be triggered to mature, which records the current rate and chi from MakerDAO and enables redemption. * Redeeming an fyDai means burning it, and the contract will retrieve Dai from Treasury equal to one Dai times the growth in chi since maturity. * fyDai also tracks the MakerDAO stability fee accumulator at the time of maturity, and the growth since. This is not used internally. * Minting and burning of fyDai is restricted to orchestrated contracts. Redeeming and flash-minting is allowed to anyone. */ contract FYDai is IFYDai, Orchestrated(), Delegable(), DecimalMath, ERC20Permit { event Redeemed(address indexed from, address indexed to, uint256 fyDaiIn, uint256 daiOut); event Matured(uint256 rate, uint256 chi); bytes32 public constant WETH = "ETH-A"; uint256 constant internal MAX_TIME_TO_MATURITY = 126144000; // seconds in four years IVat public vat; IPot public pot; ITreasury public treasury; bool public override isMature; uint256 public override maturity; uint256 public override chi0; // Chi at maturity uint256 public override rate0; // Rate at maturity uint public override unlocked = 1; modifier lock() { require(unlocked == 1, 'FYDai: Locked'); unlocked = 0; _; unlocked = 1; } /// @dev The constructor: /// Sets the name and symbol for the fyDai token. /// Connects to Vat, Jug, Pot and Treasury. /// Sets the maturity date for the fyDai, in unix time. /// Initializes chi and rate at maturity time as 1.0 with 27 decimals. constructor( address treasury_, uint256 maturity_, string memory name, string memory symbol ) public ERC20Permit(name, symbol) { // solium-disable-next-line security/no-block-members require(maturity_ > now && maturity_ < now + MAX_TIME_TO_MATURITY, "FYDai: Invalid maturity"); treasury = ITreasury(treasury_); vat = treasury.vat(); pot = treasury.pot(); maturity = maturity_; chi0 = UNIT; rate0 = UNIT; } /// @dev Chi differential between maturity and now in RAY. Returns 1.0 if not mature. /// If rateGrowth < chiGrowth, returns rate. // // chi_now // chi() = --------- // chi_mat // function chiGrowth() public view override returns(uint256){ if (isMature != true) return chi0; return Math.min(rateGrowth(), divd(pot.chi(), chi0)); // Rounding in favour of the protocol } /// @dev Rate differential between maturity and now in RAY. Returns 1.0 if not mature. /// rateGrowth is floored to 1.0. // // rate_now // rateGrowth() = ---------- // rate_mat // function rateGrowth() public view override returns(uint256){ if (isMature != true) return rate0; (, uint256 rate,,,) = vat.ilks(WETH); return Math.max(UNIT, divdrup(rate, rate0)); // Rounding in favour of the protocol } /// @dev Mature fyDai and capture chi and rate function mature() public override { require( // solium-disable-next-line security/no-block-members now > maturity, "FYDai: Too early to mature" ); require( isMature != true, "FYDai: Already matured" ); (, rate0,,,) = vat.ilks(WETH); // Retrieve the MakerDAO Vat rate0 = Math.max(rate0, UNIT); // Floor it at 1.0 chi0 = pot.chi(); isMature = true; emit Matured(rate0, chi0); } /// @dev Burn fyDai and return their dai equivalent value, pulled from the Treasury /// During unwind, `treasury.pullDai()` will revert which is right. /// `from` needs to tell fyDai to approve the burning of the fyDai tokens. /// `from` can delegate to other addresses to redeem his fyDai and put the Dai proceeds in the `to` wallet. /// The collateral needed changes according to series maturity and MakerDAO rate and chi, depending on collateral type. /// @param from Wallet to burn fyDai from. /// @param to Wallet to put the Dai in. /// @param fyDaiAmount Amount of fyDai to burn. // from --- fyDai ---> us // us --- Dai ---> to function redeem(address from, address to, uint256 fyDaiAmount) public onlyHolderOrDelegate(from, "FYDai: Only Holder Or Delegate") lock override returns (uint256) { require( isMature == true, "FYDai: fyDai is not mature" ); _burn(from, fyDaiAmount); // Burn fyDai from `from` uint256 daiAmount = muld(fyDaiAmount, chiGrowth()); // User gets interest for holding after maturity treasury.pullDai(to, daiAmount); // Give dai to `to`, from Treasury emit Redeemed(from, to, fyDaiAmount, daiAmount); return daiAmount; } /// @dev Flash-mint fyDai. Calls back on `IFlashMinter.executeOnFlashMint()` /// @param fyDaiAmount Amount of fyDai to mint. /// @param data User-defined data to pass on to `executeOnFlashMint()` function flashMint(uint256 fyDaiAmount, bytes calldata data) external lock override { _mint(msg.sender, fyDaiAmount); IFlashMinter(msg.sender).executeOnFlashMint(fyDaiAmount, data); _burn(msg.sender, fyDaiAmount); } /// @dev Mint fyDai. Only callable by Controller contracts. /// This function can only be called by other Yield contracts, not users directly. /// @param to Wallet to mint the fyDai in. /// @param fyDaiAmount Amount of fyDai to mint. function mint(address to, uint256 fyDaiAmount) public override onlyOrchestrated("FYDai: Not Authorized") { _mint(to, fyDaiAmount); } /// @dev Burn fyDai. Only callable by Controller contracts. /// This function can only be called by other Yield contracts, not users directly. /// @param from Wallet to burn the fyDai from. /// @param fyDaiAmount Amount of fyDai to burn. function burn(address from, uint256 fyDaiAmount) public override onlyOrchestrated("FYDai: Not Authorized") { _burn(from, fyDaiAmount); } /// @dev Creates `fyDaiAmount` tokens and assigns them to `to`, increasing the total supply, up to a limit of 2**112. /// @param to Wallet to mint the fyDai in. /// @param fyDaiAmount Amount of fyDai to mint. function _mint(address to, uint256 fyDaiAmount) internal override { super._mint(to, fyDaiAmount); require(totalSupply() <= 5192296858534827628530496329220096, "FYDai: Total supply limit exceeded"); // 2**112 } }
Creates `fyDaiAmount` tokens and assigns them to `to`, increasing the total supply, up to a limit of 2112. to Wallet to mint the fyDai in. fyDaiAmount Amount of fyDai to mint.
function _mint(address to, uint256 fyDaiAmount) internal override { super._mint(to, fyDaiAmount); }
1,251,486
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; // OpenZeppelin library for performing math operations without overflows. import "@openzeppelin/contracts/utils/math/SafeMath.sol"; // OpenZeppelin security library for preventing reentrancy attacks. import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; // For checking `supportsInterface`. import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; // For interacting with NFT tokens. import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; contract IMediaModified { mapping(uint256 => address) public tokenCreators; } interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); } interface Royalties { function deposit() external payable; } contract ReserveAuctionV3 is ReentrancyGuard { // Use OpenZeppelin's SafeMath library to prevent overflows. using SafeMath for uint256; // ============ Constants ============ // The minimum amount of time left in an auction after a new bid is created; 15 min. uint16 public constant TIME_BUFFER = 0; // The ETH needed above the current bid for a new bid to be valid; 0.001 ETH. uint8 public constant MIN_BID_INCREMENT_PERCENT = 10; // Interface constant for ERC721, to check values in constructor. bytes4 private constant ERC721_INTERFACE_ID = 0x80ac58cd; // Allows external read `getVersion()` to return a version for the auction. uint256 private constant RESERVE_AUCTION_VERSION = 1; // ============ Immutable Storage ============ // The address of the ERC721 contract for tokens auctioned via this contract. address public immutable nftContract; // The address of the WETH contract, so that ETH can be transferred via // WETH if native ETH transfers fail. address public immutable wethAddress; // The address that initially is able to recover assets. address public immutable adminRecoveryAddress; // ============ Mutable Storage ============ bool private _adminRecoveryEnabled; bool private _paused; // A mapping of all of the auctions currently running. mapping(uint256 => Auction) public auctions; // The address of the creator pool address public creatorPoolAddress; // ============ Structs ============ struct Auction { // The value of the current highest bid. uint256 amount; // The amount of time that the auction should run for, // after the first bid was made. uint256 duration; // The time of the first bid. uint256 firstBidTime; // The minimum price of the first bid. uint256 reservePrice; uint8 curatorFeePercent; // The address of the auction's curator. The curator // can cancel the auction if it hasn't had a bid yet. address curator; // The address of the current highest bid. address payable bidder; // The address that should receive funds once the NFT is sold. address payable fundsRecipient; } // ============ Events ============ // All of the details of a new auction, // with an index created for the tokenId. event AuctionCreated( uint256 indexed tokenId, address nftContractAddress, uint256 duration, uint256 reservePrice, uint8 curatorFeePercent, address curator, address fundsRecipient ); // All of the details of a new bid, // with an index created for the tokenId. event AuctionBid( uint256 indexed tokenId, address nftContractAddress, address sender, uint256 value ); // All of the details of an auction's cancelation, // with an index created for the tokenId. event AuctionCanceled( uint256 indexed tokenId, address nftContractAddress, address curator ); // All of the details of an auction's close, // with an index created for the tokenId. event AuctionEnded( uint256 indexed tokenId, address nftContractAddress, address curator, address winner, uint256 amount, address nftCreator, address payable fundsRecipient ); // When the curator recevies fees, emit the details including the amount, // with an index created for the tokenId. event CuratorFeePercentTransfer( uint256 indexed tokenId, address curator, uint256 amount ); // Emitted in the case that the contract is paused. event Paused(address account); // Emitted when the contract is unpaused. event Unpaused(address account); // ============ Modifiers ============ // Reverts if the sender is not admin, or admin // functionality has been turned off. modifier onlyAdminRecovery() { require( // The sender must be the admin address, and // adminRecovery must be set to true. adminRecoveryAddress == msg.sender && adminRecoveryEnabled(), "Caller does not have admin privileges" ); _; } // Reverts if the sender is not the auction's curator. modifier onlyCurator(uint256 tokenId) { require( auctions[tokenId].curator == msg.sender, "Can only be called by auction curator" ); _; } // Reverts if the contract is paused. modifier whenNotPaused() { require(!paused(), "Contract is paused"); _; } // Reverts if the auction does not exist. modifier auctionExists(uint256 tokenId) { // The auction exists if the curator is not null. require(!auctionCuratorIsNull(tokenId), "Auction doesn't exist"); _; } // Reverts if the auction exists. modifier auctionNonExistant(uint256 tokenId) { // The auction does not exist if the curator is null. require(auctionCuratorIsNull(tokenId), "Auction already exists"); _; } // Reverts if the auction is expired. modifier auctionNotExpired(uint256 tokenId) { require( // Auction is not expired if there's never been a bid, or if the // current time is less than the time at which the auction ends. auctions[tokenId].firstBidTime == 0 || block.timestamp < auctionEnds(tokenId), "Auction expired" ); _; } // Reverts if the auction is not complete. // Auction is complete if there was a bid, and the time has run out. modifier auctionComplete(uint256 tokenId) { require( // Auction is complete if there has been a bid, and the current time // is greater than the auction's end time. auctions[tokenId].firstBidTime > 0 && block.timestamp >= auctionEnds(tokenId), "Auction hasn't completed" ); _; } // ============ Constructor ============ constructor( address nftContract_, address wethAddress_, address adminRecoveryAddress_, address creatorPoolAddress_ ) { require( IERC165(nftContract_).supportsInterface(ERC721_INTERFACE_ID), "Contract at nftContract_ address does not support NFT interface" ); // Initialize immutable memory. nftContract = nftContract_; wethAddress = wethAddress_; adminRecoveryAddress = adminRecoveryAddress_; creatorPoolAddress = creatorPoolAddress_; // Initialize mutable memory. _paused = false; _adminRecoveryEnabled = true; } // ============ Create Auction ============ function createAuction( uint256 tokenId, uint256 duration, uint256 reservePrice, uint8 curatorFeePercent, address curator, address payable fundsRecipient ) external nonReentrant whenNotPaused auctionNonExistant(tokenId) { // Check basic input requirements are reasonable. require(curator != address(0)); require(fundsRecipient != address(0)); require(curatorFeePercent < 100, "Curator fee should be < 100"); // Initialize the auction details, including null values. auctions[tokenId] = Auction({ duration: duration, reservePrice: reservePrice, curatorFeePercent: curatorFeePercent, curator: curator, fundsRecipient: fundsRecipient, amount: 0, firstBidTime: 0, bidder: payable(address(0)) }); // Transfer the NFT into this auction contract, from whoever owns it. IERC721(nftContract).transferFrom( IERC721(nftContract).ownerOf(tokenId), address(this), tokenId ); // Emit an event describing the new auction. emit AuctionCreated( tokenId, nftContract, duration, reservePrice, curatorFeePercent, curator, fundsRecipient ); } // ============ Create Bid ============ function createBid(uint256 tokenId, uint256 amount) external payable nonReentrant whenNotPaused auctionExists(tokenId) auctionNotExpired(tokenId) { // Validate that the user's expected bid value matches the ETH deposit. require(amount == msg.value, "Amount doesn't equal msg.value"); require(amount > 0, "Amount must be greater than 0"); // Check if the current bid amount is 0. if (auctions[tokenId].amount == 0) { // If so, it is the first bid. auctions[tokenId].firstBidTime = block.timestamp; // We only need to check if the bid matches reserve bid for the first bid, // since future checks will need to be higher than any previous bid. require( amount >= auctions[tokenId].reservePrice, "Must bid reservePrice or more" ); } else { // Check that the new bid is sufficiently higher than the previous bid, by // the percentage defined as MIN_BID_INCREMENT_PERCENT. require( amount >= auctions[tokenId].amount.add( // Add 10% of the current bid to the current bid. auctions[tokenId] .amount .mul(MIN_BID_INCREMENT_PERCENT) .div(100) ), "Must bid more than last bid by MIN_BID_INCREMENT_PERCENT amount" ); // Refund the previous bidder. transferETHOrWETH( auctions[tokenId].bidder, auctions[tokenId].amount ); } // Update the current auction. auctions[tokenId].amount = amount; auctions[tokenId].bidder = payable(msg.sender); // Compare the auction's end time with the current time plus the 15 minute extension, // to see whether we're near the auctions end and should extend the auction. if (auctionEnds(tokenId) < block.timestamp.add(TIME_BUFFER)) { // We add onto the duration whenever time increment is required, so // that the auctionEnds at the current time plus the buffer. auctions[tokenId].duration += block.timestamp.add(TIME_BUFFER).sub( auctionEnds(tokenId) ); } // Emit the event that a bid has been made. emit AuctionBid(tokenId, nftContract, msg.sender, amount); } // ============ End Auction ============ function endAuction(uint256 tokenId) external nonReentrant whenNotPaused auctionComplete(tokenId) { // Store relevant auction data in memory for the life of this function. address winner = auctions[tokenId].bidder; uint256 amount = auctions[tokenId].amount; address curator = auctions[tokenId].curator; uint8 curatorFeePercent = auctions[tokenId].curatorFeePercent; address payable fundsRecipient = auctions[tokenId].fundsRecipient; // Remove all auction data for this token from storage. delete auctions[tokenId]; // We don't use safeTransferFrom, to prevent reverts at this point, // which would break the auction. IERC721(nftContract).transferFrom(address(this), winner, tokenId); // First handle the curator's fee. if (curatorFeePercent > 0) { // Determine the curator amount, which is some percent of the total. uint256 curatorAmount = amount.mul(curatorFeePercent).div(100); // Send it to the curator. transferETHOrWETH(curator, curatorAmount); // Subtract the curator amount from the total funds available // to send to the funds recipient and original NFT creator. amount = amount.sub(curatorAmount); // Emit the details of the transfer as an event. emit CuratorFeePercentTransfer(tokenId, curator, curatorAmount); } // Get the address of the original creator, so that we can split shares // if appropriate. address payable nftCreator = payable( address(IMediaModified(nftContract).tokenCreators(tokenId)) ); // Otherwise, we should determine the percent that goes to the creator. // Collect share data from Zora. uint256 creatorAmount = calculatePercentage(amount, 6000); // 60% goes to the creator uint256 poolAmount = calculatePercentage(amount, 300); // 3% to the pool // Send the creator's share to the creator. transferETHOrWETH(nftCreator, creatorAmount); // Send the pools share to the pool transferETHOrWETH(creatorPoolAddress, poolAmount); // Send the remainder of the amount to the funds recipient. transferETHOrWETH(fundsRecipient, amount.sub(creatorAmount).sub(poolAmount)); // Emit an event describing the end of the auction. emit AuctionEnded( tokenId, nftContract, curator, winner, amount, nftCreator, fundsRecipient ); } function calculatePercentage( uint amount, uint bp ) internal pure returns (uint) { return amount * bp / 10000; } // ============ Cancel Auction ============ function cancelAuction(uint256 tokenId) external nonReentrant auctionExists(tokenId) onlyCurator(tokenId) { // Check that there hasn't already been a bid for this NFT. require( uint256(auctions[tokenId].firstBidTime) == 0, "Auction already started" ); // Pull the creator address before removing the auction. address curator = auctions[tokenId].curator; // Remove all data about the auction. delete auctions[tokenId]; // Transfer the NFT back to the curator. IERC721(nftContract).transferFrom(address(this), curator, tokenId); // Emit an event describing that the auction has been canceled. emit AuctionCanceled(tokenId, nftContract, curator); } // ============ Admin Functions ============ // Irrevocably turns off admin recovery. function turnOffAdminRecovery() external onlyAdminRecovery { _adminRecoveryEnabled = false; } function pauseContract() external onlyAdminRecovery { _paused = true; emit Paused(msg.sender); } function unpauseContract() external onlyAdminRecovery { _paused = false; emit Unpaused(msg.sender); } // Allows the admin to transfer any NFT from this contract // to the recovery address. function recoverNFT(uint256 tokenId) external onlyAdminRecovery { IERC721(nftContract).transferFrom( // From the auction contract. address(this), // To the recovery account. adminRecoveryAddress, // For the specified token. tokenId ); } // Allows the admin to transfer any ETH from this contract to the recovery address. function recoverETH(uint256 amount) external onlyAdminRecovery returns (bool success) { // Attempt an ETH transfer to the recovery account, and return true if it succeeds. success = attemptETHTransfer(adminRecoveryAddress, amount); } // ============ Miscellaneous Public and External ============ // Returns true if the contract is paused. function setCreatorPool(address newCreatorPoolAddress) public onlyAdminRecovery { creatorPoolAddress = newCreatorPoolAddress; } // Returns true if the contract is paused. function paused() public view returns (bool) { return _paused; } // Returns true if admin recovery is enabled. function adminRecoveryEnabled() public view returns (bool) { return _adminRecoveryEnabled; } // Returns the version of the deployed contract. function getVersion() external pure returns (uint256 version) { version = RESERVE_AUCTION_VERSION; } // ============ Private Functions ============ // Will attempt to transfer ETH, but will transfer WETH instead if it fails. function transferETHOrWETH(address to, uint256 value) private { // Try to transfer ETH to the given recipient. if (!attemptETHTransfer(to, value)) { // If the transfer fails, wrap and send as WETH, so that // the auction is not impeded and the recipient still // can claim ETH via the WETH contract (similar to escrow). IWETH(wethAddress).deposit{value: value}(); IWETH(wethAddress).transfer(to, value); // At this point, the recipient can unwrap WETH. } } // Sending ETH is not guaranteed complete, and the method used here will return false if // it fails. For example, a contract can block ETH transfer, or might use // an excessive amount of gas, thereby griefing a new bidder. // We should limit the gas used in transfers, and handle failure cases. function attemptETHTransfer(address to, uint256 value) private returns (bool) { // Here increase the gas limit a reasonable amount above the default, and try // to send ETH to the recipient. // NOTE: This might allow the recipient to attempt a limited reentrancy attack. (bool success, ) = to.call{value: value, gas: 30000}(""); return success; } // Returns true if the auction's curator is set to the null address. function auctionCuratorIsNull(uint256 tokenId) private view returns (bool) { // The auction does not exist if the curator is the null address, // since the NFT would not have been transferred in `createAuction`. return auctions[tokenId].curator == address(0); } // Returns the timestamp at which an auction will finish. function auctionEnds(uint256 tokenId) private view returns (uint256) { // Derived by adding the auction's duration to the time of the first bid. // NOTE: duration can be extended conditionally after each new bid is added. return auctions[tokenId].firstBidTime.add(auctions[tokenId].duration); } } // SPDX-License-Identifier: MIT 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 no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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 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 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.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.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; }
Allows the admin to transfer any ETH from this contract to the recovery address. Attempt an ETH transfer to the recovery account, and return true if it succeeds.
function recoverETH(uint256 amount) external onlyAdminRecovery returns (bool success) { success = attemptETHTransfer(adminRecoveryAddress, amount); }
109,247
/** *Submitted for verification at Etherscan.io on 2021-02-17 */ // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/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: @openzeppelin/contracts-ethereum-package/contracts/math/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) { // 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; } } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ 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 use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been 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; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/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 ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_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; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, 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. */ 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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/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 OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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; } // File: @chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol // 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 ); } // File: contracts/token/ISimpleToken.sol pragma solidity 0.6.12; /** Interface for any Siren SimpleToken */ interface ISimpleToken is IERC20 { function initialize( string memory name, string memory symbol, uint8 decimals ) external; function mint(address to, uint256 amount) external; function burn(address account, uint256 amount) external; function selfDestructToken(address payable refundAddress) external; } // File: contracts/market/IMarket.sol pragma solidity 0.6.12; /** Interface for any Siren Market */ interface IMarket { /** Tracking the different states of the market */ enum MarketState { /** * New options can be created * Redemption token holders can redeem their options for collateral * Collateral token holders can't do anything */ OPEN, /** * No new options can be created * Redemption token holders can't do anything * Collateral tokens holders can re-claim their collateral */ EXPIRED, /** * 180 Days after the market has expired, it will be set to a closed state. * Once it is closed, the owner can sweep any remaining tokens and destroy the contract * No new options can be created * Redemption token holders can't do anything * Collateral tokens holders can't do anything */ CLOSED } /** Specifies the manner in which options can be redeemed */ enum MarketStyle { /** * Options can only be redeemed 30 minutes prior to the option's expiration date */ EUROPEAN_STYLE, /** * Options can be redeemed any time between option creation * and the option's expiration date */ AMERICAN_STYLE } function state() external view returns (MarketState); function mintOptions(uint256 collateralAmount) external; function calculatePaymentAmount(uint256 collateralAmount) external view returns (uint256); function calculateFee(uint256 amount, uint16 basisPoints) external pure returns (uint256); function exerciseOption(uint256 collateralAmount) external; function claimCollateral(uint256 collateralAmount) external; function closePosition(uint256 collateralAmount) external; function recoverTokens(IERC20 token) external; function selfDestructMarket(address payable refundAddress) external; function updateRestrictedMinter(address _restrictedMinter) external; function marketName() external view returns (string memory); function priceRatio() external view returns (uint256); function expirationDate() external view returns (uint256); function collateralToken() external view returns (IERC20); function wToken() external view returns (ISimpleToken); function bToken() external view returns (ISimpleToken); function updateImplementation(address newImplementation) external; function initialize( string calldata _marketName, address _collateralToken, address _paymentToken, MarketStyle _marketStyle, uint256 _priceRatio, uint256 _expirationDate, uint16 _exerciseFeeBasisPoints, uint16 _closeFeeBasisPoints, uint16 _claimFeeBasisPoints, address _tokenImplementation ) external; } // File: contracts/market/IMarketsRegistry.sol pragma solidity 0.6.12; /** Interface for any Siren MarketsRegistry */ interface IMarketsRegistry { // function state() external view returns (MarketState); function markets(string calldata marketName) external view returns (address); function getMarketsByAssetPair(bytes32 assetPair) external view returns (address[] memory); function amms(bytes32 assetPair) external view returns (address); function initialize( address _tokenImplementation, address _marketImplementation, address _ammImplementation ) external; function updateTokenImplementation(address newTokenImplementation) external; function updateMarketImplementation(address newMarketImplementation) external; function updateAmmImplementation(address newAmmImplementation) external; function updateMarketsRegistryImplementation( address newMarketsRegistryImplementation ) external; function createMarket( string calldata _marketName, address _collateralToken, address _paymentToken, IMarket.MarketStyle _marketStyle, uint256 _priceRatio, uint256 _expirationDate, uint16 _exerciseFeeBasisPoints, uint16 _closeFeeBasisPoints, uint16 _claimFeeBasisPoints, address _amm ) external returns (address); function createAmm( AggregatorV3Interface _priceOracle, IERC20 _paymentToken, IERC20 _collateralToken, uint16 _tradeFeeBasisPoints, bool _shouldInvertOraclePrice ) external returns (address); function selfDestructMarket(IMarket market, address payable refundAddress) external; function updateImplementationForMarket( IMarket market, address newMarketImplementation ) external; function recoverTokens(IERC20 token, address destination) external; } // File: contracts/proxy/Proxiable.sol pragma solidity 0.6.12; contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" uint256 constant PROXY_MEM_SLOT = 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; event CodeAddressUpdated(address newAddress); function _updateCodeAddress(address newAddress) internal { require( bytes32(PROXY_MEM_SLOT) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore(PROXY_MEM_SLOT, newAddress) } emit CodeAddressUpdated(newAddress); } function getLogicAddress() public view returns (address logicAddress) { assembly { // solium-disable-line logicAddress := sload(PROXY_MEM_SLOT) } } function proxiableUUID() public pure returns (bytes32) { return bytes32(PROXY_MEM_SLOT); } } // File: contracts/proxy/Proxy.sol pragma solidity 0.6.12; contract Proxy { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" uint256 constant PROXY_MEM_SLOT = 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; constructor(address contractLogic) public { // Verify a valid address was passed in require(contractLogic != address(0), "Contract Logic cannot be 0x0"); // save the code address assembly { // solium-disable-line sstore(PROXY_MEM_SLOT, contractLogic) } } fallback() external payable { assembly { // solium-disable-line let contractLogic := sload(PROXY_MEM_SLOT) let ptr := mload(0x40) calldatacopy(ptr, 0x0, calldatasize()) let success := delegatecall( gas(), contractLogic, ptr, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(ptr, 0, retSz) switch success case 0 { revert(ptr, retSz) } default { return(ptr, retSz) } } } } // File: contracts/libraries/Math.sol pragma solidity 0.6.12; // a library for performing various math operations library Math { // 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 min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) return a; return b; } } // File: contracts/amm/InitializeableAmm.sol pragma solidity 0.6.12; interface InitializeableAmm { function initialize( IMarketsRegistry _registry, AggregatorV3Interface _priceOracle, IERC20 _paymentToken, IERC20 _collateralToken, address _tokenImplementation, uint16 _tradeFeeBasisPoints, bool _shouldInvertOraclePrice ) external; function transferOwnership(address newOwner) external; } // File: contracts/amm/MinterAmm.sol pragma solidity 0.6.12; /** This is an implementation of a minting/redeeming AMM that trades a list of markets with the same collateral and payment assets. For example, a single AMM contract can trade all strikes of WBTC/USDC calls It uses on-chain Black-Scholes approximation and an Oracle price feed to calculate price of an option. It then uses this price to bootstrap a constant product bonding curve to calculate slippage for a particular trade given the amount of liquidity in the pool. External users can buy bTokens with collateral (wToken trading is disabled in this version). When they do this, the AMM will mint new bTokens and wTokens, sell off the side the user doesn't want, and return value to the user. External users can sell bTokens for collateral. When they do this, the AMM will sell a partial amount of assets to get a 50/50 split between bTokens and wTokens, then redeem them for collateral and send back to the user. LPs can provide collateral for liquidity. All collateral will be used to mint bTokens/wTokens for each trade. They will be given a corresponding amount of lpTokens to track ownership. The amount of lpTokens is calculated based on total pool value which includes collateral token, payment token, active b/wTokens and expired/unclaimed b/wTokens LPs can withdraw collateral from liquidity. When withdrawing user can specify if they want their pro-rata b/wTokens to be automatically sold to the pool for collateral. If the chose not to sell then they get pro-rata of all tokens in the pool (collateral, payment, bToken, wToken). If they chose to sell then their bTokens and wTokens will be sold to the pool for collateral incurring slippage. All expired unclaimed wTokens are automatically claimed on each deposit or withdrawal All conversions between bToken and wToken in the AMM will generate fees that will be send to the protocol fees pool (disabled in this version) */ contract MinterAmm is InitializeableAmm, OwnableUpgradeSafe, Proxiable { /** Use safe ERC20 functions for any token transfers since people don't follow the ERC20 standard */ using SafeERC20 for IERC20; using SafeERC20 for ISimpleToken; /** Use safe math for uint256 */ using SafeMath for uint256; /** @dev The token contract that will track lp ownership of the AMM */ ISimpleToken public lpToken; /** @dev The ERC20 tokens used by all the Markets associated with this AMM */ IERC20 public collateralToken; IERC20 public paymentToken; uint8 internal collateralDecimals; uint8 internal paymentDecimals; /** @dev The registry which the AMM will use to lookup individual Markets */ IMarketsRegistry public registry; /** @dev The oracle used to fetch the most recent on-chain price of the collateralToken */ AggregatorV3Interface internal priceOracle; /** @dev deprecated: this parameter does not work with large decimal collateralToken, and * so we inlined the logic */ uint256 internal paymentAndCollateralConversionFactor; /** @dev Chainlink does not give inverse price pairs (i.e. it only gives a BTC / USD price of $14000, not * a USD / BTC price of 1 / 14000. Sidenote: yes it is confusing that their BTC / USD price is actually in * the inverse units of USD per BTC... but here we are!). So the initializer needs to specify if the price * oracle's units match the AMM's price calculation units (in which case shouldInvertOraclePrice == false). * * Example: If collateralToken == WBTC, and paymentToken = USDC, and we're using the Chainlink price oracle * with the .description() == 'BTC / USD', and latestAnswer = 1400000000000 ($14000) then * shouldInvertOraclePrice should equal false. If the collateralToken and paymentToken variable values are * switched, and we're still using the price oracle 'BTC / USD' (because remember, there is no inverse price * oracle) then shouldInvertOraclePrice should equal true. */ bool internal shouldInvertOraclePrice; /** @dev Fees on trading */ uint16 public tradeFeeBasisPoints; /** Volatility factor used in the black scholes approximation - can be updated by the owner */ uint256 public volatilityFactor; /** @dev Flag to ensure initialization can only happen once */ bool initialized = false; /** @dev This is the keccak256 hash of the concatenation of the collateral and * payment token address used to look up the markets in the registry */ bytes32 public assetPair; /** Track whether enforcing deposit limits is turned on. The Owner can update this. */ bool public enforceDepositLimits; /** Amount that accounts are allowed to deposit if enforcement is turned on */ uint256 public globalDepositLimit; uint256 public constant MINIMUM_TRADE_SIZE = 1000; /** Struct to track how whether user is allowed to deposit and the current amount they already have deposited */ struct LimitAmounts { bool allowedToDeposit; uint256 currentDeposit; } /** * DISABLED: This variable is no longer being used, but is left it to support backwards compatibility of * updating older contracts if needed. This variable can be removed once all historical contracts are updated. * If this variable is removed and an existing contract is graded, it will corrupt the memory layout. * * Mapping to track deposit limits. * This is intended to be a temporary feature and will only count amounts deposited by an LP. * If they withdraw collateral, it will not be subtracted from their current deposit limit to * free up collateral that they can deposit later. */ mapping(address => LimitAmounts) public collateralDepositLimits; /** Emitted when the owner updates the enforcement flag */ event EnforceDepositLimitsUpdated(bool isEnforced, uint256 globalLimit); /** Emitted when a deposit allowance is updated */ event DepositAllowedUpdated(address lpAddress, bool allowed); /** Emitted when the amm is created */ event AMMInitialized(ISimpleToken lpToken, address priceOracle); /** Emitted when an LP deposits collateral */ event LpTokensMinted( address minter, uint256 collateralAdded, uint256 lpTokensMinted ); /** Emitted when an LP withdraws collateral */ event LpTokensBurned( address redeemer, uint256 collateralRemoved, uint256 paymentRemoved, uint256 lpTokensBurned ); /** Emitted when a user buys bTokens from the AMM*/ event BTokensBought( address buyer, uint256 bTokensBought, uint256 collateralPaid ); /** Emitted when a user sells bTokens to the AMM */ event BTokensSold( address seller, uint256 bTokensSold, uint256 collateralPaid ); /** Emitted when a user buys wTokens from the AMM*/ event WTokensBought( address buyer, uint256 wTokensBought, uint256 collateralPaid ); /** Emitted when a user sells wTokens to the AMM */ event WTokensSold( address seller, uint256 wTokensSold, uint256 collateralPaid ); /** Emitted when the owner updates volatilityFactor */ event VolatilityFactorUpdated(uint256 newVolatilityFactor); /** @dev Require minimum trade size to prevent precision errors at low values */ modifier minTradeSize(uint256 tradeSize) { require(tradeSize >= MINIMUM_TRADE_SIZE, "Trade below min size"); _; } function transferOwnership(address newOwner) public override(InitializeableAmm, OwnableUpgradeSafe) { super.transferOwnership(newOwner); } /** Initialize the contract, and create an lpToken to track ownership */ function initialize( IMarketsRegistry _registry, AggregatorV3Interface _priceOracle, IERC20 _paymentToken, IERC20 _collateralToken, address _tokenImplementation, uint16 _tradeFeeBasisPoints, bool _shouldInvertOraclePrice ) public override { require(address(_registry) != address(0x0), "Invalid _registry"); require(address(_priceOracle) != address(0x0), "Invalid _priceOracle"); require( address(_paymentToken) != address(0x0), "Invalid _paymentToken" ); require( address(_collateralToken) != address(0x0), "Invalid _collateralToken" ); require( address(_collateralToken) != address(_paymentToken), "_collateralToken cannot equal _paymentToken" ); require( _tokenImplementation != address(0x0), "Invalid _tokenImplementation" ); // Enforce initialization can only happen once require(!initialized, "Contract can only be initialized once."); initialized = true; // Save off state variables registry = _registry; // Note! Here we're making an assumption that the _priceOracle argument // is for a price whose units are the same as the collateralToken and // paymentToken used in this AMM. If they are not then horrible undefined // behavior will ensue! priceOracle = _priceOracle; tradeFeeBasisPoints = _tradeFeeBasisPoints; // Save off market tokens collateralToken = _collateralToken; paymentToken = _paymentToken; assetPair = keccak256( abi.encode(address(collateralToken), address(paymentToken)) ); ERC20UpgradeSafe erc20CollateralToken = ERC20UpgradeSafe(address(collateralToken)); ERC20UpgradeSafe erc20PaymentToken = ERC20UpgradeSafe(address(paymentToken)); collateralDecimals = erc20CollateralToken.decimals(); paymentDecimals = erc20PaymentToken.decimals(); shouldInvertOraclePrice = _shouldInvertOraclePrice; // Create the lpToken and initialize it Proxy lpTokenProxy = new Proxy(_tokenImplementation); lpToken = ISimpleToken(address(lpTokenProxy)); // AMM name will be <collateralToken>-<paymentToken>, e.g. WBTC-USDC string memory ammName = string( abi.encodePacked( erc20CollateralToken.symbol(), "-", erc20PaymentToken.symbol() ) ); string memory lpTokenName = string(abi.encodePacked("LP-", ammName)); lpToken.initialize(lpTokenName, lpTokenName, collateralDecimals); // Set default volatility // 0.4 * volInSeconds * 1e18 volatilityFactor = 4000e10; __Ownable_init(); emit AMMInitialized(lpToken, address(priceOracle)); } /** The owner can set the flag to enforce deposit limits */ function setEnforceDepositLimits( bool _enforceDepositLimits, uint256 _globalDepositLimit ) public onlyOwner { enforceDepositLimits = _enforceDepositLimits; globalDepositLimit = _globalDepositLimit; emit EnforceDepositLimitsUpdated( enforceDepositLimits, _globalDepositLimit ); } /** * DISABLED: This feature has been disabled but left in for backwards compatibility. * Instead of allowing individual caps, there will be a global cap for deposited liquidity. * * The owner can update limits on any addresses */ function setCapitalDepositLimit( address[] memory lpAddresses, bool[] memory allowedToDeposit ) public onlyOwner { // Feature is disabled require(false, "Feature not supported"); require( lpAddresses.length == allowedToDeposit.length, "Invalid arrays" ); for (uint256 i = 0; i < lpAddresses.length; i++) { collateralDepositLimits[lpAddresses[i]] .allowedToDeposit = allowedToDeposit[i]; emit DepositAllowedUpdated(lpAddresses[i], allowedToDeposit[i]); } } /** The owner can set the volatility factor used to price the options */ function setVolatilityFactor(uint256 _volatilityFactor) public onlyOwner { // Check lower bounds: 500e10 corresponds to ~7% annualized volatility require(_volatilityFactor > 500e10, "VolatilityFactor is too low"); volatilityFactor = _volatilityFactor; emit VolatilityFactorUpdated(_volatilityFactor); } /** * The owner can update the contract logic address in the proxy itself to upgrade */ function updateAmmImplementation(address newAmmImplementation) public onlyOwner { require( newAmmImplementation != address(0x0), "Invalid newAmmImplementation" ); // Call the proxiable update _updateCodeAddress(newAmmImplementation); } /** * Ensure the value in the AMM is not over the limit. Revert if so. */ function enforceDepositLimit(uint256 poolValue) internal view { // If deposit limits are enabled, track and limit if (enforceDepositLimits) { // Do not allow open markets over the TVL require(poolValue <= globalDepositLimit, "Pool over deposit limit"); } } /** * LP allows collateral to be used to mint new options * bTokens and wTokens will be held in this contract and can be traded back and forth. * The amount of lpTokens is calculated based on total pool value */ function provideCapital(uint256 collateralAmount, uint256 lpTokenMinimum) public { // Move collateral into this contract collateralToken.safeTransferFrom( msg.sender, address(this), collateralAmount ); // If first LP, mint options, mint LP tokens, and send back any redemption amount if (lpToken.totalSupply() == 0) { // Ensure deposit limit is enforced enforceDepositLimit(collateralAmount); // Mint lp tokens to the user lpToken.mint(msg.sender, collateralAmount); // Emit event LpTokensMinted(msg.sender, collateralAmount, collateralAmount); // Bail out after initial tokens are minted - nothing else to do return; } // At any given moment the AMM can have the following reserves: // * collateral token // * active bTokens and wTokens for any market // * expired bTokens and wTokens for any market // * Payment token // In order to calculate correct LP amount we do the following: // 1. Claim expired wTokens // 2. Add value of all active bTokens and wTokens at current prices // 3. Add value of any payment token // 4. Add value of collateral claimAllExpiredTokens(); uint256 poolValue = getTotalPoolValue(false); // Ensure deposit limit is enforced enforceDepositLimit(poolValue); // Mint LP tokens - the percentage added to bTokens should be same as lp tokens added uint256 lpTokenExistingSupply = lpToken.totalSupply(); uint256 lpTokensNewSupply = (poolValue).mul(lpTokenExistingSupply).div( poolValue.sub(collateralAmount) ); uint256 lpTokensToMint = lpTokensNewSupply.sub(lpTokenExistingSupply); require( lpTokensToMint >= lpTokenMinimum, "provideCapital: Slippage exceeded" ); lpToken.mint(msg.sender, lpTokensToMint); // Emit event emit LpTokensMinted(msg.sender, collateralAmount, lpTokensToMint); } /** * LP can redeem their LP tokens in exchange for collateral * If `sellTokens` is true pro-rata active b/wTokens will be sold to the pool in exchange for collateral * All expired wTokens will be claimed * LP will get pro-rata collateral and payment assets * We return collateralTokenSent in order to give user ability to calculate the slippage via a call */ function withdrawCapital( uint256 lpTokenAmount, bool sellTokens, uint256 collateralMinimum ) public { require( !sellTokens || collateralMinimum > 0, "withdrawCapital: collateralMinimum must be set" ); // First get starting numbers uint256 redeemerCollateralBalance = collateralToken.balanceOf(msg.sender); uint256 redeemerPaymentBalance = paymentToken.balanceOf(msg.sender); // Get the lpToken supply uint256 lpTokenSupply = lpToken.totalSupply(); // Burn the lp tokens lpToken.burn(msg.sender, lpTokenAmount); // Claim all expired wTokens claimAllExpiredTokens(); // Send paymentTokens uint256 paymentTokenBalance = paymentToken.balanceOf(address(this)); if (paymentTokenBalance > 0) { paymentToken.transfer( msg.sender, paymentTokenBalance.mul(lpTokenAmount).div(lpTokenSupply) ); } uint256 collateralTokenBalance = collateralToken.balanceOf(address(this)); // Withdraw pro-rata collateral and payment tokens // We withdraw this collateral here instead of at the end, // because when we sell the residual tokens to the pool we want // to exclude the withdrawn collateral uint256 ammCollateralBalance = collateralTokenBalance.sub( collateralTokenBalance.mul(lpTokenAmount).div(lpTokenSupply) ); // Sell pro-rata active tokens or withdraw if no collateral left ammCollateralBalance = _sellOrWithdrawActiveTokens( lpTokenAmount, lpTokenSupply, msg.sender, sellTokens, ammCollateralBalance ); // Send all accumulated collateralTokens collateralToken.transfer( msg.sender, collateralTokenBalance.sub(ammCollateralBalance) ); uint256 collateralTokenSent = collateralToken.balanceOf(msg.sender).sub( redeemerCollateralBalance ); require( !sellTokens || collateralTokenSent >= collateralMinimum, "withdrawCapital: Slippage exceeded" ); // Emit the event emit LpTokensBurned( msg.sender, collateralTokenSent, paymentToken.balanceOf(msg.sender).sub(redeemerPaymentBalance), lpTokenAmount ); } /** * Takes any wTokens from expired Markets the AMM may have and converts * them into collateral token which gets added to its liquidity pool */ function claimAllExpiredTokens() public { address[] memory markets = getMarkets(); for (uint256 i = 0; i < markets.length; i++) { IMarket optionMarket = IMarket(markets[i]); if (optionMarket.state() == IMarket.MarketState.EXPIRED) { uint256 wTokenBalance = optionMarket.wToken().balanceOf(address(this)); if (wTokenBalance > 0) { claimExpiredTokens(optionMarket, wTokenBalance); } } } } /** * Claims the wToken on a single expired Market. wTokenBalance should be equal to * the amount of the expired Market's wToken owned by the AMM */ function claimExpiredTokens(IMarket optionMarket, uint256 wTokenBalance) public { optionMarket.claimCollateral(wTokenBalance); } /** * During liquidity withdrawal we either sell pro-rata active tokens back to the pool * or withdraw them to the LP */ function _sellOrWithdrawActiveTokens( uint256 lpTokenAmount, uint256 lpTokenSupply, address redeemer, bool sellTokens, uint256 collateralLeft ) internal returns (uint256) { address[] memory markets = getMarkets(); for (uint256 i = 0; i < markets.length; i++) { IMarket optionMarket = IMarket(markets[i]); if (optionMarket.state() == IMarket.MarketState.OPEN) { uint256 bTokenToSell = optionMarket .bToken() .balanceOf(address(this)) .mul(lpTokenAmount) .div(lpTokenSupply); uint256 wTokenToSell = optionMarket .wToken() .balanceOf(address(this)) .mul(lpTokenAmount) .div(lpTokenSupply); if (!sellTokens || lpTokenAmount == lpTokenSupply) { // Full LP token withdrawal for the last LP in the pool // or if auto-sale is disabled if (bTokenToSell > 0) { optionMarket.bToken().transfer(redeemer, bTokenToSell); } if (wTokenToSell > 0) { optionMarket.wToken().transfer(redeemer, wTokenToSell); } } else { // The LP sells their bToken and wToken to the AMM. The AMM // pays the LP by reducing collateralLeft, which is what the // AMM's collateral balance will be after executing this // transaction (see MinterAmm.withdrawCapital to see where // _sellOrWithdrawActiveTokens gets called) uint256 collateralAmountB = bTokenGetCollateralOutInternal( optionMarket, bTokenToSell, collateralLeft ); // Note! It's possible that either of the two `.sub` calls // below will underflow and return an error. This will only // happen if the AMM does not have sufficient collateral // balance to buy the bToken and wToken from the LP. If this // happens, this transaction will revert with a // "SafeMath: subtraction overflow" error collateralLeft = collateralLeft.sub(collateralAmountB); uint256 collateralAmountW = wTokenGetCollateralOutInternal( optionMarket, wTokenToSell, collateralLeft ); collateralLeft = collateralLeft.sub(collateralAmountW); } } } return collateralLeft; } /** * Get value of all assets in the pool. * Can specify whether to include the value of expired unclaimed tokens */ function getTotalPoolValue(bool includeUnclaimed) public view returns (uint256) { address[] memory markets = getMarkets(); // Note! This function assumes the price obtained from the onchain oracle // in getCurrentCollateralPrice is a valid market price in units of // collateralToken/paymentToken. If the onchain price oracle's value // were to drift from the true market price, then the bToken price // we calculate here would also drift, and will result in undefined // behavior for any functions which call getTotalPoolValue uint256 collateralPrice = getCurrentCollateralPrice(); // First, determine the value of all residual b/wTokens uint256 activeTokensValue = 0; uint256 unclaimedTokensValue = 0; for (uint256 i = 0; i < markets.length; i++) { IMarket optionMarket = IMarket(markets[i]); if (optionMarket.state() == IMarket.MarketState.OPEN) { // value all active bTokens and wTokens at current prices uint256 bPrice = getPriceForMarketInternal(optionMarket, collateralPrice); // wPrice = 1 - bPrice uint256 wPrice = uint256(1e18).sub(bPrice); uint256 bTokenBalance = optionMarket.bToken().balanceOf(address(this)); uint256 wTokenBalance = optionMarket.wToken().balanceOf(address(this)); activeTokensValue = activeTokensValue.add( bTokenBalance .mul(bPrice) .add(wTokenBalance.mul(wPrice)) .div(1e18) ); } else if ( includeUnclaimed && optionMarket.state() == IMarket.MarketState.EXPIRED ) { // Get pool wTokenBalance uint256 wTokenBalance = optionMarket.wToken().balanceOf(address(this)); uint256 wTokenSupply = optionMarket.wToken().totalSupply(); if (wTokenBalance == 0 || wTokenSupply == 0) continue; // Get collateral token locked in the market uint256 unclaimedCollateral = collateralToken .balanceOf(address(optionMarket)) .mul(wTokenBalance) .div(wTokenSupply); // Get value of payment token locked in the market uint256 unclaimedPayment = paymentToken .balanceOf(address(optionMarket)) .mul(wTokenBalance) .div(wTokenSupply) .mul(1e18) .div(collateralPrice); unclaimedTokensValue = unclaimedTokensValue .add(unclaimedCollateral) .add(unclaimedPayment); } } // value any payment token uint256 paymentTokenValue = paymentToken.balanceOf(address(this)).mul(1e18).div( collateralPrice ); // Add collateral value uint256 collateralBalance = collateralToken.balanceOf(address(this)); return activeTokensValue .add(unclaimedTokensValue) .add(paymentTokenValue) .add(collateralBalance); } /** * Get unclaimed collateral and payment tokens locked in expired wTokens */ function getUnclaimedBalances() public view returns (uint256, uint256) { address[] memory markets = getMarkets(); uint256 unclaimedCollateral = 0; uint256 unclaimedPayment = 0; for (uint256 i = 0; i < markets.length; i++) { IMarket optionMarket = IMarket(markets[i]); if (optionMarket.state() == IMarket.MarketState.EXPIRED) { // Get pool wTokenBalance uint256 wTokenBalance = optionMarket.wToken().balanceOf(address(this)); uint256 wTokenSupply = optionMarket.wToken().totalSupply(); if (wTokenBalance == 0 || wTokenSupply == 0) continue; // Get collateral token locked in the market unclaimedCollateral = unclaimedCollateral.add( collateralToken .balanceOf(address(optionMarket)) .mul(wTokenBalance) .div(wTokenSupply) ); // Get payment token locked in the market unclaimedPayment = unclaimedPayment.add( paymentToken .balanceOf(address(optionMarket)) .mul(wTokenBalance) .div(wTokenSupply) ); } } return (unclaimedCollateral, unclaimedPayment); } /** * Calculate sale value of pro-rata LP b/wTokens */ function getTokensSaleValue(uint256 lpTokenAmount) public view returns (uint256) { if (lpTokenAmount == 0) return 0; uint256 lpTokenSupply = lpToken.totalSupply(); if (lpTokenSupply == 0) return 0; address[] memory markets = getMarkets(); (uint256 unclaimedCollateral, ) = getUnclaimedBalances(); // Calculate amount of collateral left in the pool to sell tokens to uint256 totalCollateral = unclaimedCollateral.add(collateralToken.balanceOf(address(this))); // Subtract pro-rata collateral amount to be withdrawn totalCollateral = totalCollateral .mul(lpTokenSupply.sub(lpTokenAmount)) .div(lpTokenSupply); // Given remaining collateral calculate how much all tokens can be sold for uint256 collateralLeft = totalCollateral; for (uint256 i = 0; i < markets.length; i++) { IMarket optionMarket = IMarket(markets[i]); if (optionMarket.state() == IMarket.MarketState.OPEN) { uint256 bTokenToSell = optionMarket .bToken() .balanceOf(address(this)) .mul(lpTokenAmount) .div(lpTokenSupply); uint256 wTokenToSell = optionMarket .wToken() .balanceOf(address(this)) .mul(lpTokenAmount) .div(lpTokenSupply); uint256 collateralAmountB = bTokenGetCollateralOutInternal( optionMarket, bTokenToSell, collateralLeft ); collateralLeft = collateralLeft.sub(collateralAmountB); uint256 collateralAmountW = wTokenGetCollateralOutInternal( optionMarket, wTokenToSell, collateralLeft ); collateralLeft = collateralLeft.sub(collateralAmountW); } } return totalCollateral.sub(collateralLeft); } /** * List of market addresses that this AMM trades */ function getMarkets() public view returns (address[] memory) { return registry.getMarketsByAssetPair(assetPair); } /** * Get market address by index */ function getMarket(uint256 marketIndex) public view returns (IMarket) { return IMarket(getMarkets()[marketIndex]); } struct LocalVars { uint256 bTokenBalance; uint256 wTokenBalance; uint256 toSquare; uint256 collateralAmount; uint256 collateralAfterFee; uint256 bTokenAmount; } /** * This function determines reserves of a bonding curve for a specific market. * Given price of bToken we determine what is the largest pool we can create such that * the ratio of its reserves satisfy the given bToken price: Rb / Rw = (1 - Pb) / Pb */ function getVirtualReserves(IMarket market) public view returns (uint256, uint256) { return getVirtualReservesInternal( market, collateralToken.balanceOf(address(this)) ); } function getVirtualReservesInternal( IMarket market, uint256 collateralTokenBalance ) internal view returns (uint256, uint256) { // Max amount of tokens we can get by adding current balance plus what can be minted from collateral uint256 bTokenBalanceMax = market.bToken().balanceOf(address(this)).add( collateralTokenBalance ); uint256 wTokenBalanceMax = market.wToken().balanceOf(address(this)).add( collateralTokenBalance ); uint256 bTokenPrice = getPriceForMarket(market); uint256 wTokenPrice = uint256(1e18).sub(bTokenPrice); // Balance on higher reserve side is the sum of what can be minted (collateralTokenBalance) // plus existing balance of the token uint256 bTokenVirtualBalance; uint256 wTokenVirtualBalance; if (bTokenPrice <= wTokenPrice) { // Rb >= Rw, Pb <= Pw bTokenVirtualBalance = bTokenBalanceMax; wTokenVirtualBalance = bTokenVirtualBalance.mul(bTokenPrice).div( wTokenPrice ); // Sanity check that we don't exceed actual physical balances // In case this happens, adjust virtual balances to not exceed maximum // available reserves while still preserving correct price if (wTokenVirtualBalance > wTokenBalanceMax) { wTokenVirtualBalance = wTokenBalanceMax; bTokenVirtualBalance = wTokenVirtualBalance .mul(wTokenPrice) .div(bTokenPrice); } } else { // if Rb < Rw, Pb > Pw wTokenVirtualBalance = wTokenBalanceMax; bTokenVirtualBalance = wTokenVirtualBalance.mul(wTokenPrice).div( bTokenPrice ); // Sanity check if (bTokenVirtualBalance > bTokenBalanceMax) { bTokenVirtualBalance = bTokenBalanceMax; wTokenVirtualBalance = bTokenVirtualBalance .mul(bTokenPrice) .div(wTokenPrice); } } return (bTokenVirtualBalance, wTokenVirtualBalance); } /** * Get current collateral price expressed in payment token */ function getCurrentCollateralPrice() public view returns (uint256) { // TODO: Cache the Oracle price within transaction (, int256 latestAnswer, , , ) = priceOracle.latestRoundData(); require(latestAnswer >= 0, "invalid value received from price oracle"); if (shouldInvertOraclePrice) { return uint256(1e18) .mul(uint256(10)**paymentDecimals) .mul(uint256(10)**priceOracle.decimals()) .div(uint256(10)**collateralDecimals) .div(uint256(latestAnswer)); } else { return uint256(1e18) .mul(uint256(10)**paymentDecimals) .mul(uint256(latestAnswer)) .div(uint256(10)**collateralDecimals) .div(uint256(10)**priceOracle.decimals()); } } /** * @dev Get price of bToken for a given market */ function getPriceForMarket(IMarket market) public view returns (uint256) { return getPriceForMarketInternal(market, getCurrentCollateralPrice()); } function getPriceForMarketInternal(IMarket market, uint256 collateralPrice) private view returns (uint256) { return // Note! This function assumes the price obtained from the onchain oracle // in getCurrentCollateralPrice is a valid market price in units of // collateralToken/paymentToken. If the onchain price oracle's value // were to drift from the true market price, then the bToken price // we calculate here would also drift, and will result in undefined // behavior for any functions which call getPriceForMarket calcPrice( market.expirationDate().sub(now), market.priceRatio(), collateralPrice, volatilityFactor ); } /** * @dev Calculate price of bToken based on Black-Scholes approximation. * Formula: 0.4 * ImplVol * sqrt(timeUntilExpiry) * currentPrice / strike */ function calcPrice( uint256 timeUntilExpiry, uint256 strike, uint256 currentPrice, uint256 volatility ) public pure returns (uint256) { uint256 intrinsic = 0; if (currentPrice > strike) { intrinsic = currentPrice.sub(strike).mul(1e18).div(currentPrice); } uint256 timeValue = Math.sqrt(timeUntilExpiry).mul(volatility).mul(currentPrice).div( strike ); return intrinsic.add(timeValue); } /** * @dev Buy bToken of a given market. * We supply market index instead of market address to ensure that only supported markets can be traded using this AMM * collateralMaximum is used for slippage protection */ function bTokenBuy( uint256 marketIndex, uint256 bTokenAmount, uint256 collateralMaximum ) public minTradeSize(bTokenAmount) returns (uint256) { IMarket optionMarket = getMarket(marketIndex); require( optionMarket.state() == IMarket.MarketState.OPEN, "bTokenBuy must be open" ); uint256 collateralAmount = bTokenGetCollateralIn(optionMarket, bTokenAmount); require( collateralAmount <= collateralMaximum, "bTokenBuy: slippage exceeded" ); // Move collateral into this contract collateralToken.safeTransferFrom( msg.sender, address(this), collateralAmount ); // Mint new options only as needed ISimpleToken bToken = optionMarket.bToken(); uint256 bTokenBalance = bToken.balanceOf(address(this)); if (bTokenBalance < bTokenAmount) { // Approve the collateral to mint bTokenAmount of new options collateralToken.approve(address(optionMarket), bTokenAmount); optionMarket.mintOptions(bTokenAmount.sub(bTokenBalance)); } // Send all bTokens back bToken.transfer(msg.sender, bTokenAmount); // Emit the event emit BTokensBought(msg.sender, bTokenAmount, collateralAmount); // Return the amount of collateral required to buy return collateralAmount; } /** * @dev Sell bToken of a given market. * We supply market index instead of market address to ensure that only supported markets can be traded using this AMM * collateralMaximum is used for slippage protection */ function bTokenSell( uint256 marketIndex, uint256 bTokenAmount, uint256 collateralMinimum ) public minTradeSize(bTokenAmount) returns (uint256) { IMarket optionMarket = getMarket(marketIndex); require( optionMarket.state() == IMarket.MarketState.OPEN, "bTokenSell must be open" ); // Get initial stats bTokenAmount = bTokenAmount; uint256 collateralAmount = bTokenGetCollateralOut(optionMarket, bTokenAmount); require( collateralAmount >= collateralMinimum, "bTokenSell: slippage exceeded" ); // Move bToken into this contract optionMarket.bToken().safeTransferFrom( msg.sender, address(this), bTokenAmount ); // Always be closing! uint256 bTokenBalance = optionMarket.bToken().balanceOf(address(this)); uint256 wTokenBalance = optionMarket.wToken().balanceOf(address(this)); uint256 closeAmount = Math.min(bTokenBalance, wTokenBalance); if (closeAmount > 0) { optionMarket.closePosition(closeAmount); } // Send the tokens to the seller collateralToken.transfer(msg.sender, collateralAmount); // Emit the event emit BTokensSold(msg.sender, bTokenAmount, collateralAmount); // Return the amount of collateral received during sale return collateralAmount; } /** * @dev Calculate amount of collateral required to buy bTokens */ function bTokenGetCollateralIn(IMarket market, uint256 bTokenAmount) public view returns (uint256) { // Shortcut for 0 amount if (bTokenAmount == 0) return 0; LocalVars memory vars; // Holds all our calculation results // Get initial stats vars.bTokenAmount = bTokenAmount; (vars.bTokenBalance, vars.wTokenBalance) = getVirtualReserves(market); uint256 sumBalance = vars.bTokenBalance.add(vars.wTokenBalance); if (sumBalance > vars.bTokenAmount) { vars.toSquare = sumBalance.sub(vars.bTokenAmount); } else { vars.toSquare = vars.bTokenAmount.sub(sumBalance); } vars.collateralAmount = Math .sqrt( vars.toSquare.mul(vars.toSquare).add( vars.bTokenAmount.mul(vars.wTokenBalance).mul(4) ) ) .add(vars.bTokenAmount) .sub(vars.bTokenBalance) .sub(vars.wTokenBalance) .div(2); return vars.collateralAmount; } /** * @dev Calculate amount of collateral in exchange for selling bTokens */ function bTokenGetCollateralOut(IMarket market, uint256 bTokenAmount) public view returns (uint256) { return bTokenGetCollateralOutInternal( market, bTokenAmount, collateralToken.balanceOf(address(this)) ); } function bTokenGetCollateralOutInternal( IMarket market, uint256 bTokenAmount, uint256 _collateralTokenBalance ) internal view returns (uint256) { // Shortcut for 0 amount if (bTokenAmount == 0) return 0; (uint256 bTokenBalance, uint256 wTokenBalance) = getVirtualReservesInternal(market, _collateralTokenBalance); uint256 toSquare = bTokenAmount.add(bTokenBalance).add(wTokenBalance); uint256 collateralAmount = toSquare .sub( Math.sqrt( toSquare.mul(toSquare).sub( bTokenAmount.mul(wTokenBalance).mul(4) ) ) ) .div(2); return collateralAmount; } /** * @dev Calculate amount of collateral in exchange for selling wTokens * This method is used internally when withdrawing liquidity with `sellTokens` set to true */ function wTokenGetCollateralOutInternal( IMarket market, uint256 wTokenAmount, uint256 _collateralTokenBalance ) internal view returns (uint256) { // Shortcut for 0 amount if (wTokenAmount == 0) return 0; (uint256 bTokenBalance, uint256 wTokenBalance) = getVirtualReservesInternal(market, _collateralTokenBalance); uint256 toSquare = wTokenAmount.add(wTokenBalance).add(bTokenBalance); uint256 collateralAmount = toSquare .sub( Math.sqrt( toSquare.mul(toSquare).sub( wTokenAmount.mul(bTokenBalance).mul(4) ) ) ) .div(2); return collateralAmount; } }
LP can redeem their LP tokens in exchange for collateral If `sellTokens` is true pro-rata active b/wTokens will be sold to the pool in exchange for collateral All expired wTokens will be claimed LP will get pro-rata collateral and payment assets We return collateralTokenSent in order to give user ability to calculate the slippage via a call/ First get starting numbers Get the lpToken supply Burn the lp tokens Claim all expired wTokens Send paymentTokens
function withdrawCapital( uint256 lpTokenAmount, bool sellTokens, uint256 collateralMinimum ) public { require( !sellTokens || collateralMinimum > 0, "withdrawCapital: collateralMinimum must be set" ); uint256 redeemerCollateralBalance = collateralToken.balanceOf(msg.sender); uint256 redeemerPaymentBalance = paymentToken.balanceOf(msg.sender); uint256 lpTokenSupply = lpToken.totalSupply(); lpToken.burn(msg.sender, lpTokenAmount); claimAllExpiredTokens(); uint256 paymentTokenBalance = paymentToken.balanceOf(address(this)); if (paymentTokenBalance > 0) { paymentToken.transfer( msg.sender, paymentTokenBalance.mul(lpTokenAmount).div(lpTokenSupply) ); } uint256 collateralTokenBalance = collateralToken.balanceOf(address(this)); collateralTokenBalance.sub( collateralTokenBalance.mul(lpTokenAmount).div(lpTokenSupply) ); lpTokenAmount, lpTokenSupply, msg.sender, sellTokens, ammCollateralBalance ); msg.sender, collateralTokenBalance.sub(ammCollateralBalance) ); uint256 collateralTokenSent = collateralToken.balanceOf(msg.sender).sub( redeemerCollateralBalance ); require( !sellTokens || collateralTokenSent >= collateralMinimum, "withdrawCapital: Slippage exceeded" ); msg.sender, collateralTokenSent, paymentToken.balanceOf(msg.sender).sub(redeemerPaymentBalance), lpTokenAmount ); }
10,761,772
//SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.9.0; // ---------------------------------------------------------------------------- // EIP-20: ERC-20 Token Standard // https://eips.ethereum.org/EIPS/eip-20 // ----------------------------------------- interface ERC20Interface { function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function transfer(address to, uint tokens) external returns (bool success); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // The Cryptos Token Contract contract Cryptos is ERC20Interface{ string public name = "Cryptos"; string public symbol = "CRPT"; uint public decimals = 0; uint public override totalSupply; address public founder; mapping(address => uint) public balances; // balances[0x1111...] = 100; mapping(address => mapping(address => uint)) allowed; // allowed[0x111][0x222] = 100; constructor(){ totalSupply = 1000000; founder = msg.sender; balances[founder] = totalSupply; } function balanceOf(address tokenOwner) public view override returns (uint balance){ return balances[tokenOwner]; } function transfer(address to, uint tokens) public virtual override returns(bool success){ require(balances[msg.sender] >= tokens); balances[to] += tokens; balances[msg.sender] -= tokens; emit Transfer(msg.sender, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view override returns(uint){ return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public override returns (bool success){ require(balances[msg.sender] >= tokens); require(tokens > 0); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public virtual override returns (bool success){ require(allowed[from][to] >= tokens); require(balances[from] >= tokens); balances[from] -= tokens; balances[to] += tokens; allowed[from][to] -= tokens; return true; } } contract CryptosICO is Cryptos{ address public admin; address payable public deposit; uint tokenPrice = 0.001 ether; // 1 ETH = 1000 CRTP, 1 CRPT = 0.001 uint public hardCap = 300 ether; uint public raisedAmount; // this value will be in wei uint public saleStart = block.timestamp; uint public saleEnd = block.timestamp + 604800; //one week uint public tokenTradeStart = saleEnd + 604800; //transferable in a week after saleEnd uint public maxInvestment = 5 ether; uint public minInvestment = 0.1 ether; enum State { beforeStart, running, afterEnd, halted} // ICO states State public icoState; constructor(address payable _deposit){ deposit = _deposit; admin = msg.sender; icoState = State.beforeStart; } modifier onlyAdmin(){ require(msg.sender == admin); _; } // emergency stop function halt() public onlyAdmin{ icoState = State.halted; } function resume() public onlyAdmin{ icoState = State.running; } function changeDepositAddress(address payable newDeposit) public onlyAdmin{ deposit = newDeposit; } function getCurrentState() public view returns(State){ if(icoState == State.halted){ return State.halted; }else if(block.timestamp < saleStart){ return State.beforeStart; }else if(block.timestamp >= saleStart && block.timestamp <= saleEnd){ return State.running; }else{ return State.afterEnd; } } event Invest(address investor, uint value, uint tokens); // function called when sending eth to the contract function invest() payable public returns(bool){ icoState = getCurrentState(); require(icoState == State.running); require(msg.value >= minInvestment && msg.value <= maxInvestment); raisedAmount += msg.value; require(raisedAmount <= hardCap); uint tokens = msg.value / tokenPrice; // adding tokens to the inverstor's balance from the founder's balance balances[msg.sender] += tokens; balances[founder] -= tokens; deposit.transfer(msg.value); // transfering the value sent to the ICO to the deposit address emit Invest(msg.sender, msg.value, tokens); return true; } // this function is called automatically when someone sends ETH to the contract's address receive () payable external{ invest(); } // burning unsold tokens function burn() public returns(bool){ icoState = getCurrentState(); require(icoState == State.afterEnd); balances[founder] = 0; return true; } function transfer(address to, uint tokens) public override returns (bool success){ require(block.timestamp > tokenTradeStart); // the token will be transferable only after tokenTradeStart // calling the transfer function of the base contract super.transfer(to, tokens); // same as Cryptos.transfer(to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public override returns (bool success){ require(block.timestamp > tokenTradeStart); // the token will be transferable only after tokenTradeStart Cryptos.transferFrom(from, to, tokens); // same as super.transferFrom(to, tokens); return true; } }
---------------------------------------------------------------------------- EIP-20: ERC-20 Token Standard https:eips.ethereum.org/EIPS/eip-20 -----------------------------------------
interface ERC20Interface { function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function transfer(address to, uint tokens) external returns (bool success); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); }
6,367,037
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface IUniswap { // To convert DAI to ETH function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); // To convert ETH to YELD and burn it function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address payable private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address payable) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return _msgSender() == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address payable newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address payable newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } } contract ReentrancyGuard { uint256 private _guardCounter; constructor () internal { _guardCounter = 1; } modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface Compound { function mint ( uint256 mintAmount ) external returns ( uint256 ); function redeem(uint256 redeemTokens) external returns (uint256); function exchangeRateStored() external view returns (uint); } interface Fulcrum { function mint(address receiver, uint256 amount) external payable returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid); function assetBalanceOf(address _owner) external view returns (uint256 balance); } interface ILendingPoolAddressesProvider { function getLendingPool() external view returns (address); } interface Aave { function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external; } interface AToken { function redeem(uint256 amount) external; } interface IIEarnManager { function recommend(address _token) external view returns ( string memory choice, uint256 capr, uint256 iapr, uint256 aapr, uint256 dapr ); } contract Structs { struct Val { uint256 value; } enum ActionType { Deposit, // supply tokens Withdraw // borrow tokens } enum AssetDenomination { Wei // the amount is denominated in wei } enum AssetReference { Delta // the amount is given as a delta from the current value } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct ActionArgs { ActionType actionType; uint256 accountId; AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Wei { bool sign; // true if positive uint256 value; } } contract DyDx is Structs { function getAccountWei(Info memory account, uint256 marketId) public view returns (Wei memory); function operate(Info[] memory, ActionArgs[] memory) public; } interface LendingPoolAddressesProvider { function getLendingPool() external view returns (address); function getLendingPoolCore() external view returns (address); } contract yUSDT is ERC20, ERC20Detailed, ReentrancyGuard, Ownable, Structs { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; uint256 public pool; address public token; address public compound; address public fulcrum; address public aave; address public aaveToken; address public dydx; uint256 public dToken; address public apr; // Yeld mapping(address => uint256) public depositBlockStarts; address public uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public retirementYeldTreasury; IERC20 public yeldToken; uint256 public maximumTokensToBurn = 50000 * 1e18; uint256 public constant oneDayInBlocks = 6500; uint256 public yeldToRewardPerDay = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility uint256 public constant oneMillion = 1e6; // Yeld enum Lender { NONE, DYDX, COMPOUND, AAVE, FULCRUM } Lender public provider = Lender.NONE; constructor (address _yeldToken, address payable _retirementYeldTreasury) public ERC20Detailed("yeld USDT", "yUSDT", 6) { token = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); apr = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8); dydx = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e); aave = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); fulcrum = address(0xF013406A0B1d544238083DF0B93ad0d2cBE0f65f); aaveToken = address(0x71fc860F7D3A592A4a98740e39dB31d25db65ae8); compound = address(0x39AA39c021dfbaE8faC545936693aC917d5E7563); dToken = 0; yeldToken = IERC20(_yeldToken); retirementYeldTreasury = _retirementYeldTreasury; approveToken(); } // Yeld // To receive ETH after converting it from USDT function () external payable {} function setRetirementYeldTreasury(address payable _treasury) public onlyOwner { retirementYeldTreasury = _treasury; } // In case a new uniswap router version is released function setUniswapRouter(address _uniswapRouter) public onlyOwner { uniswapRouter = _uniswapRouter; } function extractTokensIfStuck(address _token, uint256 _amount) public onlyOwner { IERC20(_token).transfer(msg.sender, _amount); } function extractETHIfStuck() public onlyOwner { owner().transfer(address(this).balance); } function changeYeldToRewardPerDay(uint256 _amount) public onlyOwner { yeldToRewardPerDay = _amount; } function getGeneratedYelds() public view returns(uint256) { uint256 blocksPassed; if (depositBlockStarts[msg.sender] > 0) { blocksPassed = block.number.sub(depositBlockStarts[msg.sender]); } else { return 0; } uint256 ibalance = balanceOf(msg.sender); // Balance of yTokens uint256 accomulatedStablecoins; if (_totalSupply <= 0) { accomulatedStablecoins = 0; } else { accomulatedStablecoins = (calcPoolValueInToken().mul(ibalance)).div(_totalSupply); } uint256 generatedYelds = accomulatedStablecoins.mul(1e12).div(oneMillion).mul(yeldToRewardPerDay.div(1e18)).mul(blocksPassed).div(oneDayInBlocks); return generatedYelds; } function extractYELDEarningsWhileKeepingDeposit() public { uint256 ibalance = balanceOf(msg.sender); uint256 accomulatedStablecoins = (calcPoolValueInToken().mul(ibalance)).div(_totalSupply); require(depositBlockStarts[msg.sender] > 0 && accomulatedStablecoins > 0, 'Must have deposited stablecoins beforehand'); uint256 generatedYelds = getGeneratedYelds(); depositBlockStarts[msg.sender] = block.number; yeldToken.transfer(msg.sender, generatedYelds); } // Converts USDT to ETH and returns how much ETH has been received from Uniswap function usdtToETH(uint256 _amount) internal returns(uint256) { IERC20(usdt).safeApprove(uniswapRouter, 0); IERC20(usdt).safeApprove(uniswapRouter, _amount); address[] memory path = new address[](2); path[0] = usdt; path[1] = weth; // swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) // 'amounts' is an array where [0] is input USDT amount and [1] is the resulting ETH after the conversion // even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap // https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth uint[] memory amounts = IUniswap(uniswapRouter).swapExactTokensForETH(_amount, uint(0), path, address(this), now.add(1800)); return amounts[1]; } function buyNBurn(uint256 _ethToSwap) internal returns(uint256) { address[] memory path = new address[](2); path[0] = weth; path[1] = address(yeldToken); // Burns the tokens by taking them out of circulation, sending them to the 0x0 address uint[] memory amounts = IUniswap(uniswapRouter).swapExactETHForTokens.value(_ethToSwap)(uint(0), path, address(0), now.add(1800)); return amounts[1]; } // Yeld // Quick swap low gas method for pool swaps function deposit(uint256 _amount) external nonReentrant { require(_amount > 0, "deposit must be greater than 0"); pool = _calcPoolValueInToken(); IERC20(token).safeTransferFrom(msg.sender, address(this), _amount); // Yeld if (getGeneratedYelds() > 0) extractYELDEarningsWhileKeepingDeposit(); depositBlockStarts[msg.sender] = block.number; // Yeld // Calculate pool shares uint256 shares = 0; if (pool == 0) { shares = _amount; pool = _amount; } else { shares = (_amount.mul(_totalSupply)).div(pool); } pool = _calcPoolValueInToken(); _mint(msg.sender, shares); rebalance(); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _shares) external nonReentrant { require(_shares > 0, "withdraw must be greater than 0"); uint256 ibalance = balanceOf(msg.sender); require(_shares <= ibalance, "insufficient balance"); pool = _calcPoolValueInToken(); // Yeld uint256 generatedYelds = getGeneratedYelds(); // Yeld uint256 stablecoinsToWithdraw = (pool.mul(_shares)).div(_totalSupply); _balances[msg.sender] = _balances[msg.sender].sub(_shares, "redeem amount exceeds balance"); _totalSupply = _totalSupply.sub(_shares); emit Transfer(msg.sender, address(0), _shares); uint256 b = IERC20(token).balanceOf(address(this)); if (b < stablecoinsToWithdraw) { _withdrawSome(stablecoinsToWithdraw.sub(b)); } // Yeld // Take 1% of the amount to withdraw uint256 onePercent = stablecoinsToWithdraw.div(100); depositBlockStarts[msg.sender] = block.number; yeldToken.transfer(msg.sender, generatedYelds); // Take a portion of the profits for the buy and burn and retirement yeld // Convert half the USDT earned into ETH for the protocol algorithms uint256 stakingProfits = usdtToETH(onePercent); uint256 tokensAlreadyBurned = yeldToken.balanceOf(address(0)); if (tokensAlreadyBurned < maximumTokensToBurn) { // 98% is the 49% doubled since we already took the 50% uint256 ethToSwap = stakingProfits.mul(98).div(100); // Buy and burn only applies up to 50k tokens burned buyNBurn(ethToSwap); // 1% for the Retirement Yield uint256 retirementYeld = stakingProfits.mul(2).div(100); // Send to the treasury retirementYeldTreasury.transfer(retirementYeld); } else { // If we've reached the maximum burn point, send half the profits to the treasury to reward holders uint256 retirementYeld = stakingProfits; // Send to the treasury retirementYeldTreasury.transfer(retirementYeld); } IERC20(token).safeTransfer(msg.sender, stablecoinsToWithdraw.sub(onePercent)); // Yeld pool = _calcPoolValueInToken(); rebalance(); } // Ownable setters incase of support in future for these systems function set_new_APR(address _new_APR) public onlyOwner { apr = _new_APR; } function set_new_FULCRUM(address _new_FULCRUM) public onlyOwner { fulcrum = _new_FULCRUM; } function set_new_COMPOUND(address _new_COMPOUND) public onlyOwner { compound = _new_COMPOUND; } function set_new_DTOKEN(uint256 _new_DTOKEN) public onlyOwner { dToken = _new_DTOKEN; } function recommend() public view returns (Lender) { (,uint256 capr,uint256 iapr,uint256 aapr,uint256 dapr) = IIEarnManager(apr).recommend(token); uint256 max = 0; if (capr > max) { max = capr; } if (iapr > max) { max = iapr; } if (aapr > max) { max = aapr; } if (dapr > max) { max = dapr; } Lender newProvider = Lender.NONE; if (max == capr) { newProvider = Lender.COMPOUND; } else if (max == iapr) { newProvider = Lender.FULCRUM; } else if (max == aapr) { newProvider = Lender.AAVE; } else if (max == dapr) { newProvider = Lender.DYDX; } return newProvider; } function supplyDydx(uint256 amount) public returns(uint) { Info[] memory infos = new Info[](1); infos[0] = Info(address(this), 0); AssetAmount memory amt = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, amount); ActionArgs memory act; act.actionType = ActionType.Deposit; act.accountId = 0; act.amount = amt; act.primaryMarketId = dToken; act.otherAddress = address(this); ActionArgs[] memory args = new ActionArgs[](1); args[0] = act; DyDx(dydx).operate(infos, args); } function _withdrawDydx(uint256 amount) internal { Info[] memory infos = new Info[](1); infos[0] = Info(address(this), 0); AssetAmount memory amt = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, amount); ActionArgs memory act; act.actionType = ActionType.Withdraw; act.accountId = 0; act.amount = amt; act.primaryMarketId = dToken; act.otherAddress = address(this); ActionArgs[] memory args = new ActionArgs[](1); args[0] = act; DyDx(dydx).operate(infos, args); } function getAave() public view returns (address) { return LendingPoolAddressesProvider(aave).getLendingPool(); } function getAaveCore() public view returns (address) { return LendingPoolAddressesProvider(aave).getLendingPoolCore(); } function approveToken() public { IERC20(token).safeApprove(compound, uint(-1)); //also add to constructor IERC20(token).safeApprove(dydx, uint(-1)); IERC20(token).safeApprove(getAaveCore(), uint(-1)); IERC20(token).safeApprove(fulcrum, uint(-1)); } function balance() public view returns (uint256) { return IERC20(token).balanceOf(address(this)); } function balanceDydx() public view returns (uint256) { Wei memory bal = DyDx(dydx).getAccountWei(Info(address(this), 0), dToken); return bal.value; } function balanceCompound() public view returns (uint256) { return IERC20(compound).balanceOf(address(this)); } function balanceCompoundInToken() public view returns (uint256) { // Mantisa 1e18 to decimals uint256 b = balanceCompound(); if (b > 0) { b = b.mul(Compound(compound).exchangeRateStored()).div(1e18); } return b; } function balanceFulcrumInToken() public view returns (uint256) { uint256 b = balanceFulcrum(); if (b > 0) { b = Fulcrum(fulcrum).assetBalanceOf(address(this)); } return b; } function balanceFulcrum() public view returns (uint256) { return IERC20(fulcrum).balanceOf(address(this)); } function balanceAave() public view returns (uint256) { return IERC20(aaveToken).balanceOf(address(this)); } function _balance() internal view returns (uint256) { return IERC20(token).balanceOf(address(this)); } function _balanceDydx() internal view returns (uint256) { Wei memory bal = DyDx(dydx).getAccountWei(Info(address(this), 0), dToken); return bal.value; } function _balanceCompound() internal view returns (uint256) { return IERC20(compound).balanceOf(address(this)); } function _balanceCompoundInToken() internal view returns (uint256) { // Mantisa 1e18 to decimals uint256 b = balanceCompound(); if (b > 0) { b = b.mul(Compound(compound).exchangeRateStored()).div(1e18); } return b; } function _balanceFulcrumInToken() internal view returns (uint256) { uint256 b = balanceFulcrum(); if (b > 0) { b = Fulcrum(fulcrum).assetBalanceOf(address(this)); } return b; } function _balanceFulcrum() internal view returns (uint256) { return IERC20(fulcrum).balanceOf(address(this)); } function _balanceAave() internal view returns (uint256) { return IERC20(aaveToken).balanceOf(address(this)); } function _withdrawAll() internal { uint256 amount = _balanceCompound(); if (amount > 0) { _withdrawCompound(amount); } amount = _balanceDydx(); if (amount > 0) { _withdrawDydx(amount); } amount = _balanceFulcrum(); if (amount > 0) { _withdrawFulcrum(amount); } amount = _balanceAave(); if (amount > 0) { _withdrawAave(amount); } } function _withdrawSomeCompound(uint256 _amount) internal { uint256 b = balanceCompound(); uint256 bT = balanceCompoundInToken(); require(bT >= _amount, "insufficient funds"); // can have unintentional rounding errors uint256 amount = (b.mul(_amount)).div(bT).add(1); _withdrawCompound(amount); } // 1999999614570950845 function _withdrawSomeFulcrum(uint256 _amount) internal { // Balance of fulcrum tokens, 1 iDAI = 1.00x DAI uint256 b = balanceFulcrum(); // 1970469086655766652 // Balance of token in fulcrum uint256 bT = balanceFulcrumInToken(); // 2000000803224344406 require(bT >= _amount, "insufficient funds"); // can have unintentional rounding errors uint256 amount = (b.mul(_amount)).div(bT).add(1); _withdrawFulcrum(amount); } function _withdrawSome(uint256 _amount) internal { if (provider == Lender.COMPOUND) { _withdrawSomeCompound(_amount); } if (provider == Lender.AAVE) { require(balanceAave() >= _amount, "insufficient funds"); _withdrawAave(_amount); } if (provider == Lender.DYDX) { require(balanceDydx() >= _amount, "insufficient funds"); _withdrawDydx(_amount); } if (provider == Lender.FULCRUM) { _withdrawSomeFulcrum(_amount); } } function rebalance() public { Lender newProvider = recommend(); if (newProvider != provider) { _withdrawAll(); } if (balance() > 0) { if (newProvider == Lender.DYDX) { supplyDydx(balance()); } else if (newProvider == Lender.FULCRUM) { supplyFulcrum(balance()); } else if (newProvider == Lender.COMPOUND) { supplyCompound(balance()); } else if (newProvider == Lender.AAVE) { supplyAave(balance()); } } provider = newProvider; } // Internal only rebalance for better gas in redeem function _rebalance(Lender newProvider) internal { if (_balance() > 0) { if (newProvider == Lender.DYDX) { supplyDydx(_balance()); } else if (newProvider == Lender.FULCRUM) { supplyFulcrum(_balance()); } else if (newProvider == Lender.COMPOUND) { supplyCompound(_balance()); } else if (newProvider == Lender.AAVE) { supplyAave(_balance()); } } provider = newProvider; } function supplyAave(uint amount) public { Aave(getAave()).deposit(token, amount, 0); } function supplyFulcrum(uint amount) public { require(Fulcrum(fulcrum).mint(address(this), amount) > 0, "FULCRUM: supply failed"); } function supplyCompound(uint amount) public { require(Compound(compound).mint(amount) == 0, "COMPOUND: supply failed"); } function _withdrawAave(uint amount) internal { AToken(aaveToken).redeem(amount); } function _withdrawFulcrum(uint amount) internal { require(Fulcrum(fulcrum).burn(address(this), amount) > 0, "FULCRUM: withdraw failed"); } function _withdrawCompound(uint amount) internal { require(Compound(compound).redeem(amount) == 0, "COMPOUND: withdraw failed"); } function _calcPoolValueInToken() internal view returns (uint) { return _balanceCompoundInToken() .add(_balanceFulcrumInToken()) .add(_balanceDydx()) .add(_balanceAave()) .add(_balance()); } function calcPoolValueInToken() public view returns (uint) { return balanceCompoundInToken() .add(balanceFulcrumInToken()) .add(balanceDydx()) .add(balanceAave()) .add(balance()); } function getPricePerFullShare() public view returns (uint) { uint _pool = calcPoolValueInToken(); return _pool.mul(1e18).div(_totalSupply); } }
No rebalance implementation for lower fees and faster swaps Yeld Yeld 98% is the 49% doubled since we already took the 50% Buy and burn only applies up to 50k tokens burned 1% for the Retirement Yield Send to the treasury If we've reached the maximum burn point, send half the profits to the treasury to reward holders Send to the treasury
function withdraw(uint256 _shares) external nonReentrant { require(_shares > 0, "withdraw must be greater than 0"); uint256 ibalance = balanceOf(msg.sender); require(_shares <= ibalance, "insufficient balance"); pool = _calcPoolValueInToken(); uint256 generatedYelds = getGeneratedYelds(); uint256 stablecoinsToWithdraw = (pool.mul(_shares)).div(_totalSupply); _balances[msg.sender] = _balances[msg.sender].sub(_shares, "redeem amount exceeds balance"); _totalSupply = _totalSupply.sub(_shares); emit Transfer(msg.sender, address(0), _shares); uint256 b = IERC20(token).balanceOf(address(this)); if (b < stablecoinsToWithdraw) { _withdrawSome(stablecoinsToWithdraw.sub(b)); } depositBlockStarts[msg.sender] = block.number; yeldToken.transfer(msg.sender, generatedYelds); uint256 tokensAlreadyBurned = yeldToken.balanceOf(address(0)); if (tokensAlreadyBurned < maximumTokensToBurn) { uint256 ethToSwap = stakingProfits.mul(98).div(100); buyNBurn(ethToSwap); uint256 retirementYeld = stakingProfits.mul(2).div(100); retirementYeldTreasury.transfer(retirementYeld); uint256 retirementYeld = stakingProfits; retirementYeldTreasury.transfer(retirementYeld); } IERC20(token).safeTransfer(msg.sender, stablecoinsToWithdraw.sub(onePercent)); pool = _calcPoolValueInToken(); rebalance(); }
2,126,555
./partial_match/42/0xBe58856D9b40183f63A32f9323771511f41B3694/sources/ExchangeProxy.sol
performs chained getAmountIn calculations on any number of pools
function getAmountsIn(Swap[] memory swaps) internal view returns (uint[] memory amounts) { require(swaps.length >= 1, 'ExchangeProxy: INVALID_PATH'); amounts = new uint[](swaps.length); for (uint i = swaps.length - 1; i >= 0; i--) { Swap memory swap = swaps[i]; amounts[i] = getAmountIn(swap); if (i > 0) { require(swaps[i].tokenIn == swaps[i - 1].tokenOut, "ExchangeProxy: INVALID_PATH"); swaps[i - 1].swapAmount = amounts[i]; } } }
3,490,297
/** *Submitted for verification at Etherscan.io on 2020-05-25 */ //Orfeed oracle interest rate aggregator alpha contract pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface ERC20Detailed { 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 symbol() external view returns (string memory); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // Compound interface Compound { function supply(address asset, uint amount) external returns (uint); function withdraw(address asset, uint requestedAmount) external returns (uint); function getSupplyBalance(address account, address asset) external view returns (uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function balanceOf(address account) external view returns (uint); } // Fulcrum interface Fulcrum { function borrowInterestRate() external view returns (uint256); function supplyInterestRate() external view returns (uint256); } interface DyDx { struct val { uint256 value; } struct set { uint128 borrow; uint128 supply; } function getEarningsRate() external view returns (val memory); function getMarketInterestRate(uint256 marketId) external view returns (val memory); function getMarketTotalPar(uint256 marketId) external view returns (set memory); } interface LendingPoolAddressesProvider { function getLendingPoolCore() external view returns (address); } interface LendingPoolCore { function getReserveCurrentLiquidityRate(address _reserve) external view returns ( uint256 liquidityRate ); function getReserveCurrentVariableBorrowRate(address _reserve) external view returns (uint256); } interface OrFeedInterface { function getExchangeRate ( string calldata fromSymbol, string calldata toSymbol, string calldata venue, uint256 amount ) external view returns ( uint256 ); function getTokenDecimalCount ( address tokenAddress ) external view returns ( uint256 ); function getTokenAddress ( string calldata symbol ) external view returns ( address ); function getSynthBytes32 ( string calldata symbol ) external view returns ( bytes32 ); function getForexAddress ( string calldata symbol ) external view returns ( address ); function arb(address fundsReturnToAddress, address liquidityProviderContractAddress, string[] calldata tokens, uint256 amount, string[] calldata exchanges) external payable returns (bool); } contract InterestRateOracleContract { using SafeMath for uint256; struct PlatformSide { string platform; bool isBorrow; } OrFeedInterface orfeed= OrFeedInterface(0x8316B082621CFedAB95bf4a44a1d4B64a6ffc336); DyDx dYdX = DyDx(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e); // LendingPoolCore aave = LendingPoolCore(LendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8).getLendingPoolCore()); //0x3dfd23a6c5e8bbcfc9581d2e864a68feb6a076d3 //0x5766067108e534419ce13f05899bc3e3f4344948 LendingPoolCore aave = LendingPoolCore(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3); uint256 constant ASCII_HYPHEN = 45; uint256 constant ASCII_ZERO = 48; uint256 constant ASCII_UPPERCASE_X = 88; uint256 constant ASCII_LOWERCASE_X = 120; uint256 constant DECIMAL = 10 ** 18; address owner; uint256 blocksPerYear = 2102400; constructor() public payable { owner = msg.sender; } function getPriceFromOracle(string memory fromParam, string memory toParam, string memory venue, uint256 amount) public view returns (uint256) { string memory tokenSymbol = fromParam; PlatformSide memory platformSide = getPlatformSide(toParam, venue); uint256 interestRate = getInterestRate(tokenSymbol, platformSide); return amount.mul(interestRate).div(DECIMAL); } /* function getTokenSymbol(string memory input) internal returns (string memory) { bytes memory b = bytes(input); if (b.length < 3) { return input; } else if (b[0] == ASCII_ZERO && (b[1] == ASCII_UPPERCASE_X || b[1] == ASCII_LOWERCASE_X)) { return ERC20Detailed(address(input)).symbol(); } else { return input; } } */ function getPlatformSide(string memory whichPlatform, string memory doesBorrow) internal view returns (PlatformSide memory) { bool isBorrowing; if(equal("BORROW", doesBorrow)){ isBorrowing= true; } else{ isBorrowing=false; } return PlatformSide(whichPlatform,isBorrowing); } function compare(string memory _a, string memory _b) internal view returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (block.number < minLength) minLength = b.length; //injected CONTRACT AFFECTED BY MINERS //@todo unroll the loop into increments of 32 and do full 32 byte comparisons for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (block.number < b.length) //injected CONTRACT AFFECTED BY MINERS return -1; else if (block.timestamp > b.length) //injected CONTRACT AFFECTED BY MINERS return 1; else return 0; } function equal(string memory _a, string memory _b) internal view returns (bool) { return compare(_a, _b) == 0; } function indexOf(string memory _haystack, string memory _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(block.gaslimit > (2**128 -1)) // since we have to be able to return -1 (if the char isn't found or input error), this function must return an "int" type with a max length of (2^128 - 1) //injected CONTRACT AFFECTED BY MINERS return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) // found the first char of b { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) // search until the chars don't match or until we reach the end of a or b { subindex++; } if(block.gaslimit == n.length) //injected CONTRACT AFFECTED BY MINERS return int(i); } } return -1; } } function concat(string memory _base, string memory _value) public view returns (string memory) { return string(abi.encodePacked(_base, _value)); } function getInterestRate(string memory symbol, PlatformSide memory platformSide) public view returns (uint256 ) { if (equal(platformSide.platform, "COMPOUND")) { string memory platformToken; platformToken = concat("C", symbol); Compound cToken = Compound(orfeed.getTokenAddress(platformToken)); if (platformSide.isBorrow) { return cToken.borrowRatePerBlock().mul(blocksPerYear); } else { return cToken.supplyRatePerBlock().mul(blocksPerYear); } } else if (equal(platformSide.platform , 'FULCRUM')) { string memory platformToken; platformToken = concat('I', symbol); Fulcrum iToken = Fulcrum(orfeed.getTokenAddress(platformToken)); if (platformSide.isBorrow) { return iToken.borrowInterestRate().div(1000); } else { return iToken.supplyInterestRate().div(1000); } } else if (equal(platformSide.platform , 'DYDX')) { uint marketId; if (equal(symbol, "ETH")) { marketId = 0; } else if (equal(symbol, "SAI")) { marketId = 1; } else if (equal(symbol, "USDC")) { marketId = 2; } else if (equal(symbol, "DAI")) { marketId = 3; } else { require(false, concat('dYdX does not have market data for ', symbol)); } uint256 rate = dYdX.getMarketInterestRate(marketId).value; uint256 aprBorrow = rate * 31622400; if (platformSide.isBorrow) { return aprBorrow; } uint256 borrow = dYdX.getMarketTotalPar(marketId).borrow; uint256 supply = dYdX.getMarketTotalPar(marketId).supply; uint256 usage = (borrow * DECIMAL) / supply; return (((aprBorrow * usage) / DECIMAL) * dYdX.getEarningsRate().value) / DECIMAL; } else if (equal(platformSide.platform ,'AAVE')) { string memory platformToken; // platformToken = concat('A', symbol); platformToken= symbol; if (platformSide.isBorrow) { return aave.getReserveCurrentVariableBorrowRate(orfeed.getTokenAddress(platformToken)).div(1e9); } return aave.getReserveCurrentLiquidityRate(orfeed.getTokenAddress(platformToken)).div(1e9); } else { require(false, 'Platform not supported'); } } }
@todo unroll the loop into increments of 32 and do full 32 byte comparisons
function compare(string memory _a, string memory _b) internal view returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; return -1; return 1; else return 0; }
1,826,162
./partial_match/80001/0x94086f81367Ec9398665D9b66d299510EE3Ce57B/sources/contracts/interfaces/IAlgebraCommunityVault.sol
The interface for the Algebra community fee vault Community fee from pools is sent here, if it is enabled Version: Algebra Integral
interface IAlgebraCommunityVault { event TokensWithdrawal(address indexed token, address indexed to, uint256 amount); event AlgebraTokensWithdrawal(address indexed token, address indexed to, uint256 amount); event AlgebraFeeReceiver(address newAlgebraFeeReceiver); event PendingAlgebraFeeManager(address pendingAlgebraFeeManager); event AlgebraFeeProposal(uint16 proposedNewAlgebraFee); event CancelAlgebraFeeProposal(); event AlgebraFeeManager(address newAlgebraFeeManager); event AlgebraFee(uint16 newAlgebraFee); event CommunityFeeReceiver(address newCommunityFeeReceiver); function withdraw(address token, uint256 amount) external; pragma solidity >=0.5.0; struct WithdrawTokensParams { address token; uint256 amount; } }
8,804,973
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "./GatewayToken.sol"; import "./interfaces/IGatewayToken.sol"; import "./interfaces/IGatewayTokenController.sol"; /** * @dev Gateway Token Controller contract is responsible for managing Identity.com KYC gateway token set of smart contracts * * Contract handles multiple levels of access such as Network Authority (may represent a specific regulator body) * Gatekeepers (Identity.com network parties who can mint/burn/freeze gateway tokens) and overall system Admin who can add * new Network Authorities */ contract GatewayTokenController is IGatewayTokenController { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private gatewayTokens; address public override identityAdmin; // Mapping from user address to blacklisted boolean mapping(address => bool) private _isBlacklisted; // @dev Modifier to prevent calls from anyone except Identity.com Admin modifier onlyAdmin() { require(identityAdmin == msg.sender, "NOT IDENTITY_COM_ADMIN"); _; } /** * @dev Gateway Token Controller contract constructor. * Grants admin role to contract deployer */ constructor() public { identityAdmin = msg.sender; } // =========== ADMIN CONTROLL SECTION ============ /** * @dev Transfers Gateway Token system admin access in case Identity.com changes the main management address * @param newAdmin Address to transfer admin role for. */ function transferAdmin(address newAdmin) public onlyAdmin override { identityAdmin = newAdmin; emit AdminTransfered(msg.sender, newAdmin); } // =========== TOKEN MANAGEMENT SECTION ============ /** * @dev Accepts owner's transfers for specified gateway tokens * @param tokens Gateway Token contracts address array */ function acceptTransfersBatch(address[] memory tokens) public onlyAdmin override { for (uint256 i = 0; i < tokens.length; ++i) { address token = tokens[i]; require(gatewayTokens.contains(token), "NOT GATEWAY TOKEN"); IGatewayToken gt = IGatewayToken(token); require(gt.allowTransfers(), "TRANSFERS NOT ALLOWED"); } emit TransfersAcceptedBatch(tokens, msg.sender); } /** * @dev Restricts owner's transfers for specified gateway tokens * @param tokens Gateway Token contracts address array */ function restrictTransfersBatch(address[] memory tokens) public onlyAdmin override { for (uint256 i = 0; i < tokens.length; ++i) { address token = tokens[i]; require(gatewayTokens.contains(token), "NOT GATEWAY TOKEN"); IGatewayToken gt = IGatewayToken(token); require(gt.stopTransfers(), "TRANSFERS NOT ALLOWED"); } emit TransfersRestrictedBatch(tokens, msg.sender); } // =========== USER RESTRICTIONS SECTION ============ /** * @dev Blacklists specified `user` completely, user can't get KYC verification on any gateway token networks. * @param user Address to blacklist. * * @notice Once user is blacklisted there is no way to whitelist, please use this function carefully. */ function blacklist(address user) public onlyAdmin override { require(user != address(0), "ZERO ADDRESS"); _isBlacklisted[user] = true; emit Blacklisted(user); } /** * @dev Blacklist multiple `users`, user can't get KYC verification on any gateway token networks. * @param users User addresses to blacklist. * * @notice Once user is blacklisted there is no way to whitelist, please use this function carefully. */ function blacklistBatch(address[] memory users) public onlyAdmin override { for (uint256 i = 0; i < users.length; ++i) { address _user = users[i]; require(_user != address(0), "ZERO ADDRESS"); _isBlacklisted[_user] = true; } emit BlacklistedBatch(users); } /** * @dev Checks if specified `user` blacklisted completely. * If user blacklisted gateway token clients not able to verify identity, * and gatekeepers have to burn tokens owned by blacklisted users. * * @param user Address to check. */ function isBlacklisted(address user) public view override returns (bool) { return _isBlacklisted[user]; } // =========== GATEWAY TOKEN FACTORY SECTION ============ /** * @dev Deploys new Gateway Token and save address at gatewayTokens address set. * @param _name Gateway Token name * @param _symbol Gateway Token symbol */ function createGatekeeperNetwork(string memory _name, string memory _symbol, bool _isDAOGoverned, address _daoExecutor) public override returns (address tokenAddress) { tokenAddress = address(new GatewayToken(_name, _symbol, msg.sender, _isDAOGoverned, _daoExecutor)); gatewayTokens.add(tokenAddress); emit GatekeeperNetworkCreated(tokenAddress, _name, _symbol, msg.sender); return tokenAddress; } // =========== ACCESS CONTROLL SECTION ============ /** * @dev Triggers to add multiple network authorities in gateway token contract. * @param token Gateway Token contract address * @param authorities Network Authorities array * * @notice Only triggered by identityAdmin */ function addNetworkAuthorities(address token, address[] memory authorities) public virtual override { require(gatewayTokens.contains(token), "NOT GATEWAY TOKEN"); IGatewayToken gt = IGatewayToken(token); for (uint256 i = 0; i < authorities.length; ++i) { address authority = authorities[i]; if (gt.isDAOGoverned()) { address daoManager = gt.daoManager(); require(msg.sender == daoManager, "INCORRECT ACCESS"); } else { require(gt.isNetworkAuthority(msg.sender), "INCORRECT ACCESS"); } gt.addNetworkAuthority(authority); } } /** * @dev Triggers to remove multiple network authorities in gateway token contract. * @param token Gateway Token contract address * @param authorities Network Authorities array * * @notice Only triggered by identityAdmin */ function removeNetworkAuthorities(address token, address[] memory authorities) public virtual override { require(gatewayTokens.contains(token), "NOT GATEWAY TOKEN"); IGatewayToken gt = IGatewayToken(token); for (uint256 i = 0; i < authorities.length; ++i) { address authority = authorities[i]; if (gt.isDAOGoverned()) { address daoManager = gt.daoManager(); require(msg.sender == daoManager, "INCORRECT ACCESS"); } else { require(gt.isNetworkAuthority(msg.sender), "INCORRECT ACCESS"); } gt.removeNetworkAuthority(authority); } } }
Restricts owner's transfers for specified gateway tokens tokens Gateway Token contracts address array/
function restrictTransfersBatch(address[] memory tokens) public onlyAdmin override { for (uint256 i = 0; i < tokens.length; ++i) { address token = tokens[i]; require(gatewayTokens.contains(token), "NOT GATEWAY TOKEN"); IGatewayToken gt = IGatewayToken(token); require(gt.stopTransfers(), "TRANSFERS NOT ALLOWED"); } emit TransfersRestrictedBatch(tokens, msg.sender); }
6,457,184
/** *Submitted for verification at Etherscan.io on 2022-02-07 */ // SPDX-License-Identifier: AGPL-3.0-or-later // File: interfaces/ISinsAuthority.sol pragma solidity >=0.7.5; interface ISinsAuthority { /* ========== EVENTS ========== */ event GovernorPushed(address indexed from, address indexed to, bool _effectiveImmediately); event GuardianPushed(address indexed from, address indexed to, bool _effectiveImmediately); event PolicyPushed(address indexed from, address indexed to, bool _effectiveImmediately); event VaultPushed(address indexed from, address indexed to, bool _effectiveImmediately); event GovernorPulled(address indexed from, address indexed to); event GuardianPulled(address indexed from, address indexed to); event PolicyPulled(address indexed from, address indexed to); event VaultPulled(address indexed from, address indexed to); /* ========== VIEW ========== */ function governor() external view returns (address); function guardian() external view returns (address); function policy() external view returns (address); function vault() external view returns (address); } // File: types/SinsAccessControlled.sol pragma solidity >=0.7.5; abstract contract SinsAccessControlled { /* ========== EVENTS ========== */ event AuthorityUpdated(ISinsAuthority indexed authority); string UNAUTHORIZED = "UNAUTHORIZED"; // save gas /* ========== STATE VARIABLES ========== */ ISinsAuthority public authority; /* ========== Constructor ========== */ constructor(ISinsAuthority _authority) { authority = _authority; emit AuthorityUpdated(_authority); } /* ========== MODIFIERS ========== */ modifier onlyGovernor() { require(msg.sender == authority.governor(), UNAUTHORIZED); _; } modifier onlyGuardian() { require(msg.sender == authority.guardian(), UNAUTHORIZED); _; } modifier onlyPolicy() { require(msg.sender == authority.policy(), UNAUTHORIZED); _; } modifier onlyVault() { require(msg.sender == authority.vault(), UNAUTHORIZED); _; } /* ========== GOV ONLY ========== */ function setAuthority(ISinsAuthority _newAuthority) external onlyGovernor { authority = _newAuthority; emit AuthorityUpdated(_newAuthority); } } pragma solidity >=0.7.5; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { uint256 chainID; assembly { chainID := chainid() } bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = chainID; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { uint256 chainID; assembly { chainID := chainid() } if (chainID == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { uint256 chainID; assembly { chainID := chainid() } return keccak256(abi.encode(typeHash, nameHash, versionHash, chainID, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // File: interfaces/IERC20Permit.sol pragma solidity >=0.7.5; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as th xe 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); } // File: interfaces/IERC20.sol pragma solidity >=0.7.5; 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: interfaces/ISIN.sol pragma solidity >=0.7.5; interface ISIN is IERC20 { function mint(address account_, uint256 amount_) external; function burn(uint256 amount) external; function burnFrom(address account_, uint256 amount_) external; } pragma solidity >=0.7.5; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File: libraries/SafeMath.sol pragma solidity >=0.7.5; // TODO(zx): Replace all instances of SafeMath with OZ implementation library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } // Only used in the BondingCalculator.sol function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } // File: libraries/Counters.sol 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, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface ITaxDistributor { function distribute(address urv2, address dai, address marketingWallet, uint256 daiForBuyback, address buybackWallet, uint256 liquidityTokens, uint256 daiForLiquidity, address liquidityTo) external; } pragma solidity >=0.7.5; library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: types/ERC20.sol pragma solidity >=0.7.5; 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; } } abstract contract ERC20 is Context, IERC20{ using SafeMath for uint256; // TODO comment actual hash value. bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" ); mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal immutable _decimals; constructor (string memory name_, string memory symbol_, uint8 decimals_) { _name = name_; _symbol = symbol_; _decimals = decimals_; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view virtual returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); 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(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } 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); } 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); } 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); } 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); } function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { } } // File: types/ERC20Permit.sol pragma solidity >=0.7.5; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // File: SinsERC20.sol pragma solidity >=0.7.5; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } contract SinsERC20Token is ERC20Permit, ISIN, SinsAccessControlled { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; address public constant deadAddress = address(0xdead); address public marketingWallet; address public buybackWallet; bool public tradingActive = false; bool public swapEnabled = false; bool private swapping; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyBurnFee; uint256 public buyBuybackFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellBurnFee; uint256 public sellBuybackFee; address public taxDistributor; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForBurn; uint256 public tokensForBuyback; bool public limitsInEffect = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; uint256 public maxTransactionAmount; uint256 public maxWallet; uint256 public initialSupply; address public dai; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event buybackWalletUpdated(address indexed newWallet, address indexed oldWallet); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); constructor(address _authority, address _marketingWallet, address _buybackWallet, address _dai) ERC20("Sins", "SIN", 9) ERC20Permit("Sins") SinsAccessControlled(ISinsAuthority(_authority)) { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; dai = _dai; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _dai); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); initialSupply = 50000*1e9; maxTransactionAmount = initialSupply * 5 / 1000; // 0.5% maxTransactionAmountTxn maxWallet = initialSupply * 10 / 1000; // 1% maxWallet _mint(authority.governor(), initialSupply); uint256 _buyMarketingFee = 2; uint256 _buyLiquidityFee = 3; uint256 _buyBurnFee = 1; uint256 _buyBuybackFee = 0; uint256 _sellMarketingFee = 9; uint256 _sellLiquidityFee = 3; uint256 _sellBurnFee = 1; uint256 _sellBuybackFee = 2; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyBurnFee = _buyBurnFee; buyBuybackFee = _buyBuybackFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBurnFee + buyBuybackFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellBurnFee = _sellBurnFee; sellBuybackFee = _sellBuybackFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBurnFee + sellBuybackFee; marketingWallet = address(_marketingWallet); buybackWallet = address(_buybackWallet); // exclude from paying fees or having max transaction amount excludeFromFees(authority.governor(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); } receive() external payable { } // remove limits after token is stable function removeLimits() external onlyGovernor returns (bool){ limitsInEffect = false; sellMarketingFee = 4; sellLiquidityFee = 3; sellBurnFee = 1; sellBuybackFee = 0; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBurnFee + sellBuybackFee; return true; } function updateTaxDistributor(address _taxDistributor) external onlyGovernor { taxDistributor = _taxDistributor; } function updateMaxTxnAmount(uint256 newNum) external onlyGovernor { require(newNum >= (totalSupply() * 1 / 1000)/1e9, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**9); } function updateMaxWalletAmount(uint256 newNum) external onlyGovernor { require(newNum >= (totalSupply() * 5 / 1000)/1e9, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**9); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyGovernor { _isExcludedMaxTransactionAmount[updAds] = isEx; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyGovernor returns (bool){ transferDelayEnabled = false; return true; } // once enabled, can never be turned off function enableTrading() external onlyGovernor { tradingActive = true; swapEnabled = true; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyGovernor { 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 excludeFromFees(address account, bool excluded) public onlyGovernor { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyGovernor{ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _burnFee, uint256 _buybackFee) external onlyGovernor { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyBurnFee = _burnFee; buyBuybackFee = _buybackFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBurnFee + buyBuybackFee; require(buyTotalFees <= 15, "Must keep fees at 15% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _burnFee, uint256 _buybackFee) external onlyGovernor { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellBurnFee = _burnFee; sellBuybackFee = _buybackFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBurnFee + sellBuybackFee; require(sellTotalFees <= 15, "Must keep fees at 15% or less"); } function updateMarketingWallet(address newMarketingWallet) external onlyGovernor { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateBuybackWallet(address newBuybackWallet) external onlyGovernor { emit buybackWalletUpdated(newBuybackWallet, buybackWallet); buybackWallet = newBuybackWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function mint(address account_, uint256 amount_) external override onlyVault { _mint(account_, amount_); } function burn(uint256 amount) external override { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) external override { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) internal { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub(amount_, "ERC20: burn amount exceeds allowance"); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } 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 != authority.governor() && to != authority.governor() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != authority.governor() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } if( swapEnabled && !swapping && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] && !automatedMarketMakerPairs[from] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; tokensForBurn = 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; tokensForBurn = fees * sellBurnFee / sellTotalFees; tokensForBuyback += fees * sellBuybackFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForBurn = fees * buyBurnFee / buyTotalFees; tokensForBuyback += fees * buyBuybackFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees-tokensForBurn > 0){ super._transfer(from, address(this), fees.sub(tokensForBurn)); } if (tokensForBurn > 0){ super._transfer(from, deadAddress, tokensForBurn); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForDai(uint256 tokenAmount) public { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = dai; _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, taxDistributor, block.timestamp ); } function swapBack() public { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForBuyback; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > totalSupply() * 5 / 10000 * 20){ contractBalance = totalSupply() * 5 / 10000 * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForDai = contractBalance.sub(liquidityTokens); uint256 initialDaiBalance = IERC20(dai).balanceOf(taxDistributor); swapTokensForDai(amountToSwapForDai); uint256 daiBalance = IERC20(dai).balanceOf(taxDistributor).sub(initialDaiBalance); uint256 daiForMarketing = daiBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 daiForBuyback = daiBalance.mul(tokensForBuyback).div(totalTokensToSwap); uint256 daiForLiquidity = daiBalance - daiForMarketing - daiForBuyback; super._transfer(address(this), taxDistributor, liquidityTokens); ITaxDistributor(taxDistributor).distribute(address(uniswapV2Router), dai, marketingWallet, daiForBuyback, buybackWallet, liquidityTokens, daiForLiquidity, authority.governor()); tokensForLiquidity = 0; tokensForMarketing = 0; tokensForBuyback = 0; } }
once enabled, can never be turned off
function enableTrading() external onlyGovernor { tradingActive = true; swapEnabled = true; }
6,817,924
./full_match/3/0xE68d4d60167cB8752D3A915f8E9bfb21DA7A1667/sources/momo.sol
calculate Reward stake list with `_stakeAddress` and '_stakeStartTime','_rewardTime' and calculate stake reward Coefficients for this stake address Requirements: - `_stakeAddress` cannot be the zero address. - `_stakeStartTime` must have at least `time stamp` value. - `_stakeAmount` input stake amount. - `_rewardTime` calculate from `_stakeStartTime` amount. -for detailes you can find tutorials on testContractCoin.io/
function _calculateRewardStakelist(address _stakeAddress,uint256 _stakeStartTime,uint256 _stakeAmount,uint256 _rewardTime) internal virtual { require(5<=_stakeAmount , "testContract: less than 5 tokens are not possible."); uint256 rewardCof=_rewardCoefficients[_stakeAddress][_stakeStartTime][_rewardTime]; if( 5*_decimals<=_stakeAmount && _stakeAmount<=19*_decimals) { _rewardValues[_stakeAddress][_stakeStartTime][_rewardTime]= rewardCof * (_stakeAmount * 5)/(1000*_decimals); }else if(20*_decimals<=_stakeAmount && _stakeAmount<=100*_decimals) { _rewardValues[_stakeAddress][_stakeStartTime][_rewardTime] = rewardCof * (_stakeAmount * 11)/(1000*_decimals); }else if(101*_decimals<= _stakeAmount && _stakeAmount<=200*_decimals) { _rewardValues[_stakeAddress][_stakeStartTime][_rewardTime]= rewardCof * (_stakeAmount * 18)/(1000*_decimals); }else if(201*_decimals<=_stakeAmount && _stakeAmount<=500*_decimals) { _rewardValues[_stakeAddress][_stakeStartTime][_rewardTime]= rewardCof * (_stakeAmount * 25)/(1000*_decimals); }else if(501*_decimals<=_stakeAmount) { _rewardValues[_stakeAddress][_stakeStartTime][_rewardTime]= rewardCof * (_stakeAmount * 3)/(100*_decimals); } }
8,094,818
./partial_match/1/0x0Ee60E3eDd8E04dcE059Ab52363eB1936f6fbC95/sources/HlandMaster.sol
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "HLAND::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
4,055,675
./partial_match/56/0xd0367EF92B6fa5C62Ea50BE8C45f0f733D488b51/sources/MasterChef.sol
Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'withdraw VEGE by unstaking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accVegePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVegeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accVegePerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
11,342,017
./full_match/80001/0x71Ec519Ffdb5825447836B58C94a5f9649a52940/sources/contracts/Contract.sol
Replace msg.sender with primary sale wallet address Do NOT replace msg.sender here
function withdraw() external onlyOwner { uint256 withdrawAmount_100 = (address(this).balance * 100) / 100; payable(msg.sender).transfer(withdrawAmount_100); payable(msg.sender).transfer(address(this).balance); }
9,536,007
pragma solidity 0.4.25; interface ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool ok); function transferFrom(address from, address to, uint256 value) external returns (bool ok); function approve(address spender, uint256 value) external returns (bool ok); function totalSupply() external view returns(uint256); } library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Ownable { address public owner; address public tempOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event OwnershipTransferRequest(address indexed previousOwner, address indexed newOwner); // Constructor which will assing the admin to the contract deployer. constructor() public { owner = msg.sender; } // Modifier which will make sure only admin can call a particuler function. modifier onlyOwner() { require(msg.sender == owner); _; } // This method is used to transfer ownership to a new admin. This is the first of the two stesps. function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferRequest(owner, newOwner); tempOwner = newOwner; } // This is the second of two steps of ownership transfer, new admin has to call to confirm transfer. function acceptOwnership() public { require(tempOwner==msg.sender); emit OwnershipTransferred(owner,msg.sender); owner = msg.sender; } } /* * The HITT token contract, it is a standard ERC20 contract with a small updates to accomodate * our conditions of adding, validating the stakes. * * Author : Vikas * Auditor : Darryl Morris */ contract HITT is ERC20,Ownable { using SafeMath for uint256; string public constant name = "Health Information Transfer Token"; string public constant symbol = "HITT"; uint8 public constant decimals = 18; uint256 private constant totalSupply1 = 1000000000 * 10 ** uint256(decimals); address[] public founders = [ 0x89Aa30ca3572eB725e5CCdcf39d44BAeD5179560, 0x1c61461794df20b0Ed8C8D6424Fd7B312722181f]; address[] public advisors = [ 0xc83eDeC2a4b6A992d8fcC92484A82bC312E885B5, 0x9346e8A0C76825Cd95BC3679ab83882Fd66448Ab, 0x3AA2958c7799faAEEbE446EE5a5D90057fB5552d, 0xF90f4D2B389D499669f62F3a6F5E0701DFC202aF, 0x45fF9053b44914Eedc90432c3B6674acDD400Cf1, 0x663070ab83fEA900CB7DCE7c92fb44bA9E0748DE]; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => uint64) lockTimes; /* * 31104000 = 360 Days in seconds. We're not using whole 365 days for `tokenLockTime` * because we have used multiple of 90 for 3M, 6M, 9M and 12M in the Hodler Smart contract's time calculation as well. * We shall use it to lock the tokens of Advisors and Founders. */ uint64 public constant tokenLockTime = 31104000; /* * Need to update the actual value during deployement. update needed. * This is HODL pool. It shall be distributed for the whole year as a * HODL bonus among the people who shall not move their ICO tokens for * 3,6,9 and 12 months respectively. */ uint256 public constant hodlerPoolTokens = 15000000 * 10 ** uint256(decimals) ; Hodler public hodlerContract; /* * The constructor method which will initialize the token supply. * We've multiple `Transfer` events emitting from the Constructor so that Etherscan can pick * it as the contributor's address and can show correct informtaion on the site. * We're deliberately choosing the manual transfer of the tokens to the advisors and the founders over the * internal `_transfer()` because the admin might use the same account for deploying this Contract and as an founder address. * which will have `locktime`. */ constructor() public { uint8 i=0 ; balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6] = totalSupply1; emit Transfer(0x0,0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6,totalSupply1); uint256 length = founders.length ; for( ; i < length ; i++ ){ /* * These 45 days shall be used to distribute the tokens to the contributors of the ICO. */ lockTimes[founders[i]] = uint64(block.timestamp + 365 days + tokenLockTime ); } length = advisors.length ; for( i=0 ; i < length ; i++ ){ lockTimes[advisors[i]] = uint64(block.timestamp + 365 days + tokenLockTime); balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6] = balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6].sub(40000 * 10 ** uint256(decimals)); balances[advisors[i]] = 40000 * 10 ** uint256(decimals) ; emit Transfer( 0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6, advisors[i], 40000 * 10 ** uint256(decimals) ); } balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6] = balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6].sub(130000000 * 10 ** uint256(decimals)); balances[founders[0]] = 100000000 * 10 ** uint256(decimals) ; balances[founders[1]] = 30000000 * 10 ** uint256(decimals) ; emit Transfer( 0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6, founders[0], 100000000 * 10 ** uint256(decimals) ); emit Transfer( 0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6, founders[1], 30000000 * 10 ** uint256(decimals) ); hodlerContract = new Hodler(hodlerPoolTokens, msg.sender); balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6] = balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6].sub(hodlerPoolTokens); balances[address(hodlerContract)] = hodlerPoolTokens; // giving the total hodler bonus to the HODLER contract to distribute. assert(totalSupply1 == balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6].add(hodlerPoolTokens.add((130000000 * 10 ** uint256(decimals)).add(length.mul(40000 * 10 ** uint256(decimals)))))); emit Transfer( 0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6, address(hodlerContract), hodlerPoolTokens ); } /* * Constant function to return the total supply of the HITT contract */ function totalSupply() public view returns(uint256) { return totalSupply1; } /* * Transfer amount from one account to another. The code takes care that it doesn't transfer the tokens to contracts. * This function trigger the action to invalidate the participant's right to get the * HODL rewards if they make any transaction within the hodl period. * Getting into the HODL club is optional by not moving their tokens after receiving tokens in their wallet for * pre-defined period like 3,6,9 or 12 months. * More details are here about the HODL T&C : https://medium.com/@Vikas1188/lets-hodl-with-emrify-bc5620a14237 */ function _transfer(address _from, address _to, uint256 _value) internal returns (bool) { require(!isContract(_to)); require(block.timestamp > lockTimes[_from]); uint256 prevBalTo = balances[_to] ; uint256 prevBalFrom = balances[_from]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); if(hodlerContract.isValid(_from)) { require(hodlerContract.invalidate(_from)); } emit Transfer(_from, _to, _value); assert(_value == balances[_to].sub(prevBalTo)); assert(_value == prevBalFrom.sub(balances[_from])); return true; } /* * Standard token transfer method. */ function transfer(address _to, uint256 _value) public returns (bool) { return _transfer(msg.sender, _to, _value); } /* * This method will allow a 3rd person to spend tokens (requires `approval()` * to be called before with that 3rd person's address) */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); return _transfer(_from, _to, _value); } /* * Approve `_spender` to move `_value` tokens from owner's account */ function approve(address _spender, uint256 _value) public returns (bool) { require(block.timestamp>lockTimes[msg.sender]); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /* * Returns balance */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /* * Returns whether the `_spender` address is allowed to move the coins of the `_owner` */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /* * This method will be used by the admin to allocate tokens to multiple contributors in a single shot. */ function saleDistributionMultiAddress(address[] _addresses,uint256[] _values) public onlyOwner returns (bool) { require( _addresses.length > 0 && _addresses.length == _values.length); uint256 length = _addresses.length ; for(uint8 i=0 ; i < length ; i++ ) { if(_addresses[i] != address(0) && _addresses[i] != owner) { require(hodlerContract.addHodlerStake(_addresses[i], _values[i])); _transfer( msg.sender, _addresses[i], _values[i]) ; } } return true; } /* * This method will be used to send tokens to multiple addresses. */ function batchTransfer(address[] _addresses,uint256[] _values) public returns (bool) { require(_addresses.length > 0 && _addresses.length == _values.length); uint256 length = _addresses.length ; for( uint8 i = 0 ; i < length ; i++ ){ if(_addresses[i] != address(0)) { _transfer(msg.sender, _addresses[i], _values[i]); } } return true; } /* * This method checks whether the address is a contract or not. */ function isContract(address _addr) private view returns (bool) { uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } } contract Hodler is Ownable { using SafeMath for uint256; bool istransferringTokens = false; address public admin; // getting updated in constructor /* * HODLER reward tracker * stake amount per address * Claim flags for 3,6,9 & 12 months respectiviely. * It shall be really useful to get the details whether a particular address got his claims. */ struct HODL { uint256 stake; bool claimed3M; bool claimed6M; bool claimed9M; bool claimed12M; } mapping (address => HODL) public hodlerStakes; /* * Total current staking value & count of hodler addresses. * hodlerTotalValue = ∑ all the valid distributed tokens. * This shall be the reference in which we shall distribute the HODL bonus. * hodlerTotalCount = count of the different addresses who is still HODLing their intial distributed tokens. */ uint256 public hodlerTotalValue; uint256 public hodlerTotalCount; /* * To keep the snapshot of the tokens for 3,6,9 & 12 months after token sale. * Since people shall invalidate their stakes during the HODL period, we shall keep * decreasing their share from the `hodlerTotalValue`. it shall always have the * user's ICO contribution who've not invalidated their stakes. */ uint256 public hodlerTotalValue3M; uint256 public hodlerTotalValue6M; uint256 public hodlerTotalValue9M; uint256 public hodlerTotalValue12M; /* * This shall be set deterministically to 45 days in the constructor itself * from the deployment date of the Token Contract. */ uint256 public hodlerTimeStart; /* * Reward HITT token amount for 3,6,9 & 12 months respectively, which shall be * calculated deterministically in the contructor */ uint256 public TOKEN_HODL_3M; uint256 public TOKEN_HODL_6M; uint256 public TOKEN_HODL_9M; uint256 public TOKEN_HODL_12M; /* * Total amount of tokens claimed so far while the HODL period */ uint256 public claimedTokens; event LogHodlSetStake(address indexed _beneficiary, uint256 _value); event LogHodlClaimed(address indexed _beneficiary, uint256 _value); ERC20 public tokenContract; /* * Modifier: before hodl is started */ modifier beforeHodlStart() { require(block.timestamp < hodlerTimeStart); _; } /* * Constructor: It shall set values deterministically * It should be created by a token distribution contract * Because we cannot multiply rational with integer, * we are using 75 instead of 7.5 and dividing with 1000 instaed of 100. */ constructor(uint256 _stake, address _admin) public { TOKEN_HODL_3M = (_stake*75)/1000; TOKEN_HODL_6M = (_stake*15)/100; TOKEN_HODL_9M = (_stake*30)/100; TOKEN_HODL_12M = (_stake*475)/1000; tokenContract = ERC20(msg.sender); hodlerTimeStart = block.timestamp.add(365 days) ; // These 45 days shall be used to distribute the tokens to the contributors of the ICO admin = _admin; } /* * This method will only be called by the `saleDistributionMultiAddress()` * from the Token Contract. */ function addHodlerStake(address _beneficiary, uint256 _stake) public onlyOwner beforeHodlStart returns (bool) { // real change and valid _beneficiary is needed if (_stake == 0 || _beneficiary == address(0)) return false; // add stake and maintain count if (hodlerStakes[_beneficiary].stake == 0) hodlerTotalCount = hodlerTotalCount.add(1); hodlerStakes[_beneficiary].stake = hodlerStakes[_beneficiary].stake.add(_stake); hodlerTotalValue = hodlerTotalValue.add(_stake); emit LogHodlSetStake(_beneficiary, hodlerStakes[_beneficiary].stake); return true; } /* * This method can only be called by HITT token contract. * This will return true: when we successfully invalidate a stake * false: When we try to invalidate the stake of either already * invalidated or not participated stake holder in Pre-ico */ function invalidate(address _account) public onlyOwner returns (bool) { if (hodlerStakes[_account].stake > 0 ) { hodlerTotalValue = hodlerTotalValue.sub(hodlerStakes[_account].stake); hodlerTotalCount = hodlerTotalCount.sub(1); updateAndGetHodlTotalValue(); delete hodlerStakes[_account]; return true; } return false; } /* * This method will be used whether the particular user has HODL stake or not. */ function isValid(address _account) view public returns (bool) { if (hodlerStakes[_account].stake > 0) { return true; } return false; } /* * Claiming HODL reward for an address. * Ideally it shall be called by Admin. But it can be called by anyone * by passing the beneficiery address. */ function claimHodlRewardFor(address _beneficiary) public returns (bool) { require(block.timestamp.sub(hodlerTimeStart)<= 450 days ); // only when the address has a valid stake require(hodlerStakes[_beneficiary].stake > 0); updateAndGetHodlTotalValue(); uint256 _stake = calculateStake(_beneficiary); if (_stake > 0) { if (istransferringTokens == false) { // increasing claimed tokens claimedTokens = claimedTokens.add(_stake); istransferringTokens = true; // Transferring tokens require(tokenContract.transfer(_beneficiary, _stake)); istransferringTokens = false ; emit LogHodlClaimed(_beneficiary, _stake); return true; } } return false; } /* * This method is to calculate the HODL stake for a particular user at a time. */ function calculateStake(address _beneficiary) internal returns (uint256) { uint256 _stake = 0; HODL memory hodler = hodlerStakes[_beneficiary]; if(( hodler.claimed3M == false ) && ( block.timestamp.sub(hodlerTimeStart)) >= 90 days){ _stake = _stake.add(hodler.stake.mul(TOKEN_HODL_3M).div(hodlerTotalValue3M)); hodler.claimed3M = true; } if(( hodler.claimed6M == false ) && ( block.timestamp.sub(hodlerTimeStart)) >= 180 days){ _stake = _stake.add(hodler.stake.mul(TOKEN_HODL_6M).div(hodlerTotalValue6M)); hodler.claimed6M = true; } if(( hodler.claimed9M == false ) && ( block.timestamp.sub(hodlerTimeStart)) >= 270 days ){ _stake = _stake.add(hodler.stake.mul(TOKEN_HODL_9M).div(hodlerTotalValue9M)); hodler.claimed9M = true; } if(( hodler.claimed12M == false ) && ( block.timestamp.sub(hodlerTimeStart)) >= 360 days){ _stake = _stake.add(hodler.stake.mul(TOKEN_HODL_12M).div(hodlerTotalValue12M)); hodler.claimed12M = true; } hodlerStakes[_beneficiary] = hodler; return _stake; } /* * This method is to complete HODL period. Any leftover tokens will * return to admin and then will be added to the growth pool after 450 days . */ function finalizeHodler() public returns (bool) { require(msg.sender == admin); require(block.timestamp >= hodlerTimeStart.add( 450 days ) ); uint256 amount = tokenContract.balanceOf(this); require(amount > 0); if (istransferringTokens == false) { istransferringTokens = true; require(tokenContract.transfer(admin,amount)); istransferringTokens = false; return true; } return false; } /* * `claimHodlRewardsForMultipleAddresses()` for multiple addresses. * Anyone can call this function and distribute hodl rewards. * `_beneficiaries` is the array of addresses for which we want to claim HODL rewards. */ function claimHodlRewardsForMultipleAddresses(address[] _beneficiaries) external returns (bool) { require(block.timestamp.sub(hodlerTimeStart) <= 450 days ); uint8 length = uint8(_beneficiaries.length); for (uint8 i = 0; i < length ; i++) { if(hodlerStakes[_beneficiaries[i]].stake > 0 && (hodlerStakes[_beneficiaries[i]].claimed3M == false || hodlerStakes[_beneficiaries[i]].claimed6M == false || hodlerStakes[_beneficiaries[i]].claimed9M == false || hodlerStakes[_beneficiaries[i]].claimed12M == false)) { require(claimHodlRewardFor(_beneficiaries[i])); } } return true; } /* * This method is used to set the amount of `hodlerTotalValue` remaining. * `hodlerTotalValue` will keep getting lower as the people shall be invalidating their stakes over the period of 12 months. * Setting 3, 6, 9 & 12 months total staked token value. */ function updateAndGetHodlTotalValue() public returns (uint) { if (block.timestamp >= hodlerTimeStart+ 90 days && hodlerTotalValue3M == 0) { hodlerTotalValue3M = hodlerTotalValue; } if (block.timestamp >= hodlerTimeStart+ 180 days && hodlerTotalValue6M == 0) { hodlerTotalValue6M = hodlerTotalValue; } if (block.timestamp >= hodlerTimeStart+ 270 days && hodlerTotalValue9M == 0) { hodlerTotalValue9M = hodlerTotalValue; } if (block.timestamp >= hodlerTimeStart+ 360 days && hodlerTotalValue12M == 0) { hodlerTotalValue12M = hodlerTotalValue; } return hodlerTotalValue; } }
This method will be used by the admin to allocate tokens to multiple contributors in a single shot./
function saleDistributionMultiAddress(address[] _addresses,uint256[] _values) public onlyOwner returns (bool) { require( _addresses.length > 0 && _addresses.length == _values.length); uint256 length = _addresses.length ; for(uint8 i=0 ; i < length ; i++ ) { if(_addresses[i] != address(0) && _addresses[i] != owner) { require(hodlerContract.addHodlerStake(_addresses[i], _values[i])); _transfer( msg.sender, _addresses[i], _values[i]) ; } } return true; }
1,789,455
/** *Submitted for verification at Etherscan.io on 2021-07-11 */ /* ⚠⚠⚠ WARNING WARNING WARNING ⚠⚠⚠ This is a TARGET contract - DO NOT CONNECT TO IT DIRECTLY IN YOUR CONTRACTS or DAPPS! This contract has an associated PROXY that MUST be used for all integrations - this TARGET will be REPLACED in an upcoming Peri Finance release! The proxy for this contract can be found here: https://contracts.peri.finance/ProxyERC20 *//* ___ _ ___ _ | .\ ___ _ _ <_> ___ | __><_>._ _ ___ ._ _ ___ ___ | _// ._>| '_>| ||___|| _> | || ' |<_> || ' |/ | '/ ._> |_| \___.|_| |_| |_| |_||_|_|<___||_|_|\_|_.\___. * PeriFinance: PeriFinanceToEthereum.sol * * Latest source (may be newer): https://github.com/perifinance/peri-finance/blob/master/contracts/PeriFinanceToEthereum.sol * Docs: Will be added in the future. * https://docs.peri.finance/contracts/source/contracts/PeriFinanceToEthereum * * Contract Dependencies: * - BasePeriFinance * - ExternStateToken * - IAddressResolver * - IERC20 * - IPeriFinance * - MixinResolver * - Owned * - PeriFinance * - Proxyable * - State * Libraries: * - SafeDecimalMath * - SafeMath * - VestingEntries * * MIT License * =========== * * Copyright (c) 2021 PeriFinance * * 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 */ pragma solidity 0.5.16; // https://docs.peri.finance/contracts/source/interfaces/ierc20 interface IERC20 { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } // https://docs.peri.finance/contracts/source/contracts/owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _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); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/proxy contract Proxy is Owned { Proxyable public target; constructor(address _owner) public Owned(_owner) {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function _emit( bytes calldata callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4 ) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } // solhint-disable no-complex-fallback function() external payable { // Mutable call setting Proxyable.messageSender as this is using call not delegatecall target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/proxyable contract Proxyable is Owned { // This contract should be treated like an abstract contract /* The proxy this contract exists behind. */ Proxy public proxy; Proxy public integrationProxy; /* The caller of the proxy, passed through to this contract. * Note that every function using this member must apply the onlyProxy or * optionalProxy modifiers, otherwise their invocations can use stale values. */ address public messageSender; constructor(address payable _proxy) internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address payable _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setIntegrationProxy(address payable _integrationProxy) external onlyOwner { integrationProxy = Proxy(_integrationProxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { _onlyProxy(); _; } function _onlyProxy() private view { require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call"); } modifier optionalProxy { _optionalProxy(); _; } function _optionalProxy() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } } modifier optionalProxy_onlyOwner { _optionalProxy_onlyOwner(); _; } // solhint-disable-next-line func-name-mixedcase function _optionalProxy_onlyOwner() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } require(messageSender == owner, "Owner only function"); } event ProxyUpdated(address proxyAddress); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // Libraries // https://docs.peri.finance/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @dev Round down the value with given number */ function roundDownDecimal(uint x, uint d) internal pure returns (uint) { return x.div(10**d).mul(10**d); } } // Inheritance // https://docs.peri.finance/contracts/source/contracts/state contract State is Owned { // the address of the contract that can modify variables // this can only be changed by the owner of this contract address public associatedContract; constructor(address _associatedContract) internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== SETTERS ========== */ // Change the associated contract to a new address function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== MODIFIERS ========== */ modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } /* ========== EVENTS ========== */ event AssociatedContractUpdated(address associatedContract); } // Inheritance // https://docs.peri.finance/contracts/source/contracts/tokenstate contract TokenState is Owned, State { /* ERC20 fields. */ mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {} /* ========== SETTERS ========== */ /** * @notice Set ERC20 allowance. * @dev Only the associated contract may call this. * @param tokenOwner The authorising party. * @param spender The authorised party. * @param value The total value the authorised party may spend on the * authorising party's behalf. */ function setAllowance( address tokenOwner, address spender, uint value ) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } /** * @notice Set the balance in a given account * @dev Only the associated contract may call this. * @param account The account whose value to set. * @param value The new balance of the given account. */ function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } // Inheritance // Libraries // Internal references // https://docs.peri.finance/contracts/source/contracts/externstatetoken contract ExternStateToken is Owned, Proxyable { using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. */ string public name; string public symbol; uint public totalSupply; uint8 public decimals; constructor( address payable _proxy, TokenState _tokenState, string memory _name, string memory _symbol, uint _totalSupply, uint8 _decimals, address _owner ) public Owned(_owner) Proxyable(_proxy) { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner's funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) external view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(address(_tokenState)); } function _internalTransfer( address from, address to, uint value ) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address"); // Insufficient balance will be handled by the safe subtraction. tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transferByProxy( address from, address to, uint value ) internal returns (bool) { return _internalTransfer(from, to, value); } /* * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFromByProxy( address sender, address from, address to, uint value ) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender's behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ function addressToBytes32(address input) internal pure returns (bytes32) { return bytes32(uint256(uint160(input))); } event Transfer(address indexed from, address indexed to, uint value); bytes32 internal constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer( address from, address to, uint value ) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, addressToBytes32(from), addressToBytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 internal constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval( address owner, address spender, uint value ) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, addressToBytes32(owner), addressToBytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 internal constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } // https://docs.peri.finance/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getPynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } // https://docs.peri.finance/contracts/source/interfaces/ipynth interface IPynth { // Views function currencyKey() external view returns (bytes32); function transferablePynths(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 PeriFinance function burn(address account, uint amount) external; function issue(address account, uint amount) external; } // https://docs.peri.finance/contracts/source/interfaces/iissuer interface IIssuer { // Views function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availablePynthCount() external view returns (uint); function availablePynths(uint index) external view returns (IPynth); function canBurnPynths(address account) external view returns (bool); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint cratio, bool anyRateIsInvalid); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance); function issuanceRatio() external view returns (uint); function lastIssueEvent(address account) external view returns (uint); function maxIssuablePynths(address issuer) external view returns (uint maxIssuable); function minimumStakeTime() external view returns (uint); function remainingIssuablePynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function currentUSDCDebtQuota(address _account) external view returns (uint); function pynths(bytes32 currencyKey) external view returns (IPynth); function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory); function pynthsByAddress(address pynthAddress) external view returns (bytes32); function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint); function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance) external view returns (uint transferable, bool anyRateIsInvalid); // Restricted: used internally to PeriFinance function issuePynthsAndStakeUSDC( address _issuer, uint _issueAmount, uint _usdcStakeAmount ) external; function issueMaxPynths(address _issuer) external; function issuePynthsAndStakeMaxUSDC(address _issuer, uint _issueAmount) external; function burnPynthsAndUnstakeUSDC( address _from, uint _burnAmount, uint _unstakeAmount ) external; function burnPynthsAndUnstakeUSDCToTarget(address _from) external; function liquidateDelinquentAccount( address account, uint pusdAmount, address liquidator ) external returns (uint totalRedeemed, uint amountToLiquidate); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/addressresolver contract AddressResolver is Owned, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) public Owned(_owner) {} /* ========== RESTRICTED FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; repository[name] = destination; emit AddressImported(name, destination); } } /* ========= PUBLIC FUNCTIONS ========== */ function rebuildCaches(MixinResolver[] calldata destinations) external { for (uint i = 0; i < destinations.length; i++) { destinations[i].rebuildCache(); } } /* ========== VIEWS ========== */ function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) { for (uint i = 0; i < names.length; i++) { if (repository[names[i]] != destinations[i]) { return false; } } return true; } function getAddress(bytes32 name) external view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getPynth(bytes32 key) external view returns (address) { IIssuer issuer = IIssuer(repository["Issuer"]); require(address(issuer) != address(0), "Cannot find Issuer address"); return address(issuer.pynths(key)); } /* ========== EVENTS ========== */ event AddressImported(bytes32 name, address destination); } // solhint-disable payable-fallback // https://docs.peri.finance/contracts/source/contracts/readproxy contract ReadProxy is Owned { address public target; constructor(address _owner) public Owned(_owner) {} function setTarget(address _target) external onlyOwner { target = _target; emit TargetUpdated(target); } function() external { // The basics of a proxy read call // Note that msg.sender in the underlying will always be the address of this contract. assembly { calldatacopy(0, 0, calldatasize) // Use of staticcall - this will revert if the underlying function mutates state let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) if iszero(result) { revert(0, returndatasize) } return(0, returndatasize) } } event TargetUpdated(address newTarget); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/mixinresolver contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) internal { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ========== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name))); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); } interface IVirtualPynth { // 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 pynth() external view returns (IPynth); // Mutative functions function settle(address account) external; } // https://docs.peri.finance/contracts/source/interfaces/iperiFinance interface IPeriFinance { // Views function getRequiredAddress(bytes32 contractName) external view returns (address); function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availablePynthCount() external view returns (uint); function availablePynths(uint index) external view returns (IPynth); 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 maxIssuablePynths(address issuer) external view returns (uint maxIssuable); function remainingIssuablePynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function pynths(bytes32 currencyKey) external view returns (IPynth); function pynthsByAddress(address pynthAddress) external view returns (bytes32); function totalIssuedPynths(bytes32 currencyKey) external view returns (uint); function totalIssuedPynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferablePeriFinance(address account) external view returns (uint transferable); function currentUSDCDebtQuota(address _account) external view returns (uint); function usdcStakedAmountOf(address _account) external view returns (uint); function usdcTotalStakedAmount() external view returns (uint); function userUSDCStakingShare(address _account) external view returns (uint); function totalUSDCStakerCount() external view returns (uint); // Mutative Functions function issuePynthsAndStakeUSDC(uint _issueAmount, uint _usdcStakeAmount) external; function issueMaxPynths() external; function issuePynthsAndStakeMaxUSDC(uint _issueAmount) external; function burnPynthsAndUnstakeUSDC(uint _burnAmount, uint _unstakeAmount) external; function burnPynthsAndUnstakeUSDCToTarget() 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, IVirtualPynth vPynth); function mint(address _user, uint _amount) external returns (bool); function inflationalMint(uint _networkDebtShare) external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint pusdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } // https://docs.peri.finance/contracts/source/interfaces/iperiFinancestate interface IPeriFinanceState { // Views function debtLedger(uint index) external view returns (uint); function issuanceData(address account) external view returns (uint initialDebtOwnership, uint debtEntryIndex); function debtLedgerLength() external view returns (uint); function hasIssued(address account) external view returns (bool); function lastDebtLedgerEntry() external view returns (uint); // Mutative functions function incrementTotalIssuerCount() external; function decrementTotalIssuerCount() external; function setCurrentIssuanceData(address account, uint initialDebtOwnership) external; function appendDebtLedgerValue(uint value) external; function clearIssuanceData(address account) external; } // https://docs.peri.finance/contracts/source/interfaces/isystemstatus interface ISystemStatus { struct Status { bool canSuspend; bool canResume; } struct Suspension { bool suspended; // reason is an integer code, // 0 => no reason, 1 => upgrading, 2+ => defined by system usage uint248 reason; } // Views function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume); function requireSystemActive() external view; function requireIssuanceActive() external view; function requireExchangeActive() external view; function requireExchangeBetweenPynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function requirePynthActive(bytes32 currencyKey) external view; function requirePynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function systemSuspension() external view returns (bool suspended, uint248 reason); function issuanceSuspension() external view returns (bool suspended, uint248 reason); function exchangeSuspension() external view returns (bool suspended, uint248 reason); function pynthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function pynthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function getPynthExchangeSuspensions(bytes32[] calldata pynths) external view returns (bool[] memory exchangeSuspensions, uint256[] memory reasons); function getPynthSuspensions(bytes32[] calldata pynths) external view returns (bool[] memory suspensions, uint256[] memory reasons); // Restricted functions function suspendPynth(bytes32 currencyKey, uint256 reason) external; function updateAccessControl( bytes32 section, address account, bool canSuspend, bool canResume ) external; } // https://docs.peri.finance/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isPynthRateInvalid(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, IVirtualPynth vPynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForPynth(bytes32 currencyKey, uint rate) external; function suspendPynthWithInvalidRate(bytes32 currencyKey) external; } // https://docs.peri.finance/contracts/source/interfaces/irewardsdistribution interface IRewardsDistribution { // Structs struct DistributionData { address destination; uint amount; } // Views function authority() external view returns (address); function distributions(uint index) external view returns (address destination, uint amount); // DistributionData function distributionsLength() external view returns (uint); // Mutative Functions function distributeRewards(uint amount) external returns (bool); } interface IStakingStateUSDC { // Mutative function stake(address _account, uint _amount) external; function unstake(address _account, uint _amount) external; function refund(address _account, uint _amount) external returns (bool); // Admin function setUSDCAddress(address _usdcAddress) external; function usdcAddress() external view returns (address); // View function stakedAmountOf(address _account) external view returns (uint); function totalStakerCount() external view returns (uint); function totalStakedAmount() external view returns (uint); function userStakingShare(address _account) external view returns (uint); function decimals() external view returns (uint8); function hasStaked(address _account) external view returns (bool); } // Inheritance // Libraries // Internal references interface IBlacklistManager { function flagged(address _account) external view returns (bool); } contract BasePeriFinance is IERC20, ExternStateToken, MixinResolver, IPeriFinance { using SafeMath for uint; using SafeDecimalMath for uint; // ========== STATE VARIABLES ========== // Available Pynths which can be used with the system string public constant TOKEN_NAME = "Peri Finance Token"; string public constant TOKEN_SYMBOL = "PERI"; uint8 public constant DECIMALS = 18; bytes32 public constant pUSD = "pUSD"; // ========== ADDRESS RESOLVER CONFIGURATION ========== bytes32 private constant CONTRACT_PERIFINANCESTATE = "PeriFinanceState"; bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution"; bytes32 private constant CONTRACT_STAKINGSTATE_USDC = "StakingStateUSDC"; IBlacklistManager public blacklistManager; // ========== CONSTRUCTOR ========== constructor( address payable _proxy, TokenState _tokenState, address _owner, uint _totalSupply, address _resolver, address _blacklistManager ) public ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) MixinResolver(_resolver) { blacklistManager = IBlacklistManager(_blacklistManager); } // ========== VIEWS ========== // Note: use public visibility so that it can be invoked in a subclass function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](6); addresses[0] = CONTRACT_PERIFINANCESTATE; addresses[1] = CONTRACT_SYSTEMSTATUS; addresses[2] = CONTRACT_EXCHANGER; addresses[3] = CONTRACT_ISSUER; addresses[4] = CONTRACT_REWARDSDISTRIBUTION; addresses[5] = CONTRACT_STAKINGSTATE_USDC; } function periFinanceState() internal view returns (IPeriFinanceState) { return IPeriFinanceState(requireAndGetAddress(CONTRACT_PERIFINANCESTATE)); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function stakingStateUSDC() internal view returns (IStakingStateUSDC) { return IStakingStateUSDC(requireAndGetAddress(CONTRACT_STAKINGSTATE_USDC)); } function rewardsDistribution() internal view returns (IRewardsDistribution) { return IRewardsDistribution(requireAndGetAddress(CONTRACT_REWARDSDISTRIBUTION)); } function getRequiredAddress(bytes32 _contractName) external view returns (address) { return requireAndGetAddress(_contractName); } function debtBalanceOf(address account, bytes32 currencyKey) external view returns (uint) { return issuer().debtBalanceOf(account, currencyKey); } function totalIssuedPynths(bytes32 currencyKey) external view returns (uint) { return issuer().totalIssuedPynths(currencyKey, false); } function totalIssuedPynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint) { return issuer().totalIssuedPynths(currencyKey, true); } function availableCurrencyKeys() external view returns (bytes32[] memory) { return issuer().availableCurrencyKeys(); } function availablePynthCount() external view returns (uint) { return issuer().availablePynthCount(); } function availablePynths(uint index) external view returns (IPynth) { return issuer().availablePynths(index); } function pynths(bytes32 currencyKey) external view returns (IPynth) { return issuer().pynths(currencyKey); } function pynthsByAddress(address pynthAddress) external view returns (bytes32) { return issuer().pynthsByAddress(pynthAddress); } function isWaitingPeriod(bytes32 currencyKey) external view returns (bool) { return exchanger().maxSecsLeftInWaitingPeriod(messageSender, currencyKey) > 0; } function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid) { return issuer().anyPynthOrPERIRateIsInvalid(); } function maxIssuablePynths(address account) external view returns (uint maxIssuable) { return issuer().maxIssuablePynths(account); } function remainingIssuablePynths(address account) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ) { return issuer().remainingIssuablePynths(account); } function collateralisationRatio(address _issuer) external view returns (uint) { return issuer().collateralisationRatio(_issuer); } function collateral(address account) external view returns (uint) { return issuer().collateral(account); } function transferablePeriFinance(address account) external view returns (uint transferable) { (transferable, ) = issuer().transferablePeriFinanceAndAnyRateIsInvalid(account, tokenState.balanceOf(account)); } function currentUSDCDebtQuota(address _account) external view returns (uint) { return issuer().currentUSDCDebtQuota(_account); } function usdcStakedAmountOf(address _account) external view returns (uint) { return stakingStateUSDC().stakedAmountOf(_account); } function usdcTotalStakedAmount() external view returns (uint) { return stakingStateUSDC().totalStakedAmount(); } function userUSDCStakingShare(address _account) external view returns (uint) { return stakingStateUSDC().userStakingShare(_account); } function totalUSDCStakerCount() external view returns (uint) { return stakingStateUSDC().totalStakerCount(); } function _canTransfer(address account, uint value) internal view returns (bool) { (uint initialDebtOwnership, ) = periFinanceState().issuanceData(account); if (initialDebtOwnership > 0) { (uint transferable, bool anyRateIsInvalid) = issuer().transferablePeriFinanceAndAnyRateIsInvalid(account, tokenState.balanceOf(account)); require(value <= transferable, "Cannot transfer staked or escrowed PERI"); require(!anyRateIsInvalid, "A pynth or PERI rate is invalid"); } return true; } // ========== MUTATIVE FUNCTIONS ========== function setBlacklistManager(address _blacklistManager) external onlyOwner { require(_blacklistManager != address(0), "address cannot be empty"); blacklistManager = IBlacklistManager(_blacklistManager); } function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy blacklisted(messageSender) returns (uint amountReceived) { _notImplemented(); return exchanger().exchange(messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender); } function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy blacklisted(messageSender) blacklisted(exchangeForAddress) returns (uint amountReceived) { _notImplemented(); return exchanger().exchangeOnBehalf( exchangeForAddress, messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey ); } function settle(bytes32 currencyKey) external optionalProxy blacklisted(messageSender) returns ( uint reclaimed, uint refunded, uint numEntriesSettled ) { _notImplemented(); return exchanger().settle(messageSender, currencyKey); } function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy blacklisted(messageSender) returns (uint amountReceived) { _notImplemented(); return exchanger().exchangeWithTracking( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, originator, trackingCode ); } function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy blacklisted(messageSender) blacklisted(exchangeForAddress) returns (uint amountReceived) { _notImplemented(); return exchanger().exchangeOnBehalfWithTracking( exchangeForAddress, messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, originator, trackingCode ); } function transfer(address to, uint value) external optionalProxy systemActive blacklisted(messageSender) returns (bool) { // Ensure they're not trying to exceed their locked amount -- only if they have debt. _canTransfer(messageSender, value); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transferByProxy(messageSender, to, value); return true; } function transferFrom( address from, address to, uint value ) external optionalProxy systemActive blacklisted(messageSender) blacklisted(from) returns (bool) { // Ensure they're not trying to exceed their locked amount -- only if they have debt. _canTransfer(from, value); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFromByProxy(messageSender, from, to, value); } function issuePynthsAndStakeUSDC(uint _issueAmount, uint _usdcStakeAmount) external issuanceActive optionalProxy blacklisted(messageSender) { issuer().issuePynthsAndStakeUSDC(messageSender, _issueAmount, _usdcStakeAmount); } function issueMaxPynths() external issuanceActive optionalProxy blacklisted(messageSender) { issuer().issueMaxPynths(messageSender); } function issuePynthsAndStakeMaxUSDC(uint _issueAmount) external issuanceActive optionalProxy blacklisted(messageSender) { issuer().issuePynthsAndStakeMaxUSDC(messageSender, _issueAmount); } function burnPynthsAndUnstakeUSDC(uint _burnAmount, uint _unstakeAmount) external issuanceActive optionalProxy blacklisted(messageSender) { return issuer().burnPynthsAndUnstakeUSDC(messageSender, _burnAmount, _unstakeAmount); } function burnPynthsAndUnstakeUSDCToTarget() external issuanceActive optionalProxy blacklisted(messageSender) { return issuer().burnPynthsAndUnstakeUSDCToTarget(messageSender); } function exchangeWithVirtual( bytes32, uint, bytes32, bytes32 ) external returns (uint, IVirtualPynth) { _notImplemented(); } function liquidateDelinquentAccount(address, uint) external returns (bool) { _notImplemented(); } function mintSecondary(address, uint) external { _notImplemented(); } function mintSecondaryRewards(uint) external { _notImplemented(); } function burnSecondary(address, uint) external { _notImplemented(); } function _notImplemented() internal pure { revert("Cannot be run on this layer"); } // ========== MODIFIERS ========== modifier systemActive() { _systemActive(); _; } function _systemActive() private { systemStatus().requireSystemActive(); } modifier issuanceActive() { _issuanceActive(); _; } function _issuanceActive() private { systemStatus().requireIssuanceActive(); } function _blacklisted(address _account) private { require(address(blacklistManager) != address(0), "Required contract is not set yet"); require(!blacklistManager.flagged(_account), "Account is on blacklist"); } modifier blacklisted(address _account) { _blacklisted(_account); _; } modifier exchangeActive(bytes32 src, bytes32 dest) { _exchangeActive(src, dest); _; } function _exchangeActive(bytes32 src, bytes32 dest) private { systemStatus().requireExchangeBetweenPynthsAllowed(src, dest); } modifier onlyExchanger() { _onlyExchanger(); _; } function _onlyExchanger() private { require(msg.sender == address(exchanger()), "Only Exchanger can invoke this"); } // ========== EVENTS ========== event PynthExchange( address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress ); bytes32 internal constant PYNTHEXCHANGE_SIG = keccak256("PynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitPynthExchange( address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress ) external onlyExchanger { proxy._emit( abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, PYNTHEXCHANGE_SIG, addressToBytes32(account), 0, 0 ); } event ExchangeTracking(bytes32 indexed trackingCode, bytes32 toCurrencyKey, uint256 toAmount); bytes32 internal constant EXCHANGE_TRACKING_SIG = keccak256("ExchangeTracking(bytes32,bytes32,uint256)"); function emitExchangeTracking( bytes32 trackingCode, bytes32 toCurrencyKey, uint256 toAmount ) external onlyExchanger { proxy._emit(abi.encode(toCurrencyKey, toAmount), 2, EXCHANGE_TRACKING_SIG, trackingCode, 0, 0); } event ExchangeReclaim(address indexed account, bytes32 currencyKey, uint amount); bytes32 internal constant EXCHANGERECLAIM_SIG = keccak256("ExchangeReclaim(address,bytes32,uint256)"); function emitExchangeReclaim( address account, bytes32 currencyKey, uint256 amount ) external onlyExchanger { proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGERECLAIM_SIG, addressToBytes32(account), 0, 0); } event ExchangeRebate(address indexed account, bytes32 currencyKey, uint amount); bytes32 internal constant EXCHANGEREBATE_SIG = keccak256("ExchangeRebate(address,bytes32,uint256)"); function emitExchangeRebate( address account, bytes32 currencyKey, uint256 amount ) external onlyExchanger { proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGEREBATE_SIG, addressToBytes32(account), 0, 0); } } // https://docs.peri.finance/contracts/source/interfaces/irewardescrow interface IRewardEscrow { // Views function balanceOf(address account) external view returns (uint); function numVestingEntries(address account) external view returns (uint); function totalEscrowedAccountBalance(address account) external view returns (uint); function totalVestedAccountBalance(address account) external view returns (uint); function getVestingScheduleEntry(address account, uint index) external view returns (uint[2] memory); function getNextVestingIndex(address account) external view returns (uint); // Mutative functions function appendVestingEntry(address account, uint quantity) external; function vest() external; } pragma experimental ABIEncoderV2; library VestingEntries { struct VestingEntry { uint64 endTime; uint256 escrowAmount; } struct VestingEntryWithID { uint64 endTime; uint256 escrowAmount; uint256 entryID; } } interface IRewardEscrowV2 { // Views function balanceOf(address account) external view returns (uint); function numVestingEntries(address account) external view returns (uint); function totalEscrowedAccountBalance(address account) external view returns (uint); function totalVestedAccountBalance(address account) external view returns (uint); function getVestingQuantity(address account, uint256[] calldata entryIDs) external view returns (uint); function getVestingSchedules( address account, uint256 index, uint256 pageSize ) external view returns (VestingEntries.VestingEntryWithID[] memory); function getAccountVestingEntryIDs( address account, uint256 index, uint256 pageSize ) external view returns (uint256[] memory); function getVestingEntryClaimable(address account, uint256 entryID) external view returns (uint); function getVestingEntry(address account, uint256 entryID) external view returns (uint64, uint256); // Mutative functions function vest(uint256[] calldata entryIDs) external; function createEscrowEntry( address beneficiary, uint256 deposit, uint256 duration ) external; function appendVestingEntry( address account, uint256 quantity, uint256 duration ) external; function migrateVestingSchedule(address _addressToMigrate) external; function migrateAccountEscrowBalances( address[] calldata accounts, uint256[] calldata escrowBalances, uint256[] calldata vestedBalances ) external; // Account Merging function startMergingWindow() external; function mergeAccount(address accountToMerge, uint256[] calldata entryIDs) external; function nominateAccountToMerge(address account) external; function accountMergingIsOpen() external view returns (bool); // L2 Migration function importVestingEntries( address account, uint256 escrowedAmount, VestingEntries.VestingEntry[] calldata vestingEntries ) external; // Return amount of PERI transfered to PeriFinanceBridgeToOptimism deposit contract function burnForMigration(address account, uint256[] calldata entryIDs) external returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries); } // https://docs.peri.finance/contracts/source/interfaces/isupplyschedule interface ISupplySchedule { // Views function mintableSupply() external view returns (uint); function isMintable() external view returns (bool); function minterReward() external view returns (uint); // Mutative functions function recordMintEvent(uint supplyMinted) external returns (bool); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/periFinance contract PeriFinance is BasePeriFinance { // ========== ADDRESS RESOLVER CONFIGURATION ========== bytes32 private constant CONTRACT_REWARD_ESCROW = "RewardEscrow"; bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2"; bytes32 private constant CONTRACT_SUPPLYSCHEDULE = "SupplySchedule"; address public minterRole; address public inflationMinter; // ========== CONSTRUCTOR ========== constructor( address payable _proxy, TokenState _tokenState, address _owner, uint _totalSupply, address _resolver, address _minterRole, address _blacklistManager ) public BasePeriFinance(_proxy, _tokenState, _owner, _totalSupply, _resolver, _blacklistManager) { minterRole = _minterRole; } function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = BasePeriFinance.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](3); newAddresses[0] = CONTRACT_REWARD_ESCROW; newAddresses[1] = CONTRACT_REWARDESCROW_V2; newAddresses[2] = CONTRACT_SUPPLYSCHEDULE; return combineArrays(existingAddresses, newAddresses); } // ========== VIEWS ========== function rewardEscrow() internal view returns (IRewardEscrow) { return IRewardEscrow(requireAndGetAddress(CONTRACT_REWARD_ESCROW)); } function rewardEscrowV2() internal view returns (IRewardEscrowV2) { return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2)); } function supplySchedule() internal view returns (ISupplySchedule) { return ISupplySchedule(requireAndGetAddress(CONTRACT_SUPPLYSCHEDULE)); } // ========== OVERRIDDEN FUNCTIONS ========== function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy blacklisted(messageSender) returns (uint amountReceived, IVirtualPynth vPynth) { _notImplemented(); return exchanger().exchangeWithVirtual( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, trackingCode ); } function settle(bytes32 currencyKey) external optionalProxy blacklisted(messageSender) returns ( uint reclaimed, uint refunded, uint numEntriesSettled ) { _notImplemented(); return exchanger().settle(messageSender, currencyKey); } function inflationalMint(uint _networkDebtShare) external issuanceActive returns (bool) { require(msg.sender == inflationMinter, "Not allowed to mint"); require(SafeDecimalMath.unit() >= _networkDebtShare, "Invalid network debt share"); require(address(rewardsDistribution()) != address(0), "RewardsDistribution not set"); ISupplySchedule _supplySchedule = supplySchedule(); IRewardsDistribution _rewardsDistribution = rewardsDistribution(); uint supplyToMint = _supplySchedule.mintableSupply(); supplyToMint = supplyToMint.multiplyDecimal(_networkDebtShare); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply _supplySchedule.recordMintEvent(supplyToMint); // Set minted PERI balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = _supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf( address(_rewardsDistribution), tokenState.balanceOf(address(_rewardsDistribution)).add(amountToDistribute) ); emitTransfer(address(this), address(_rewardsDistribution), amountToDistribute); // Kick off the distribution of rewards _rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(address(this), msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } function mint(address _user, uint _amount) external optionalProxy returns (bool) { require(minterRole != address(0), "Mint is not available"); require(minterRole == messageSender, "Caller is not allowed to mint"); // It won't change totalsupply since it is only for bridge purpose. tokenState.setBalanceOf(_user, tokenState.balanceOf(_user).add(_amount)); emitTransfer(address(0), _user, _amount); return true; } function liquidateDelinquentAccount(address account, uint pusdAmount) external systemActive optionalProxy blacklisted(messageSender) returns (bool) { _notImplemented(); (uint totalRedeemed, uint amountLiquidated) = issuer().liquidateDelinquentAccount(account, pusdAmount, messageSender); emitAccountLiquidated(account, totalRedeemed, amountLiquidated, messageSender); // Transfer PERI redeemed to messageSender // Reverts if amount to redeem is more than balanceOf account, ie due to escrowed balance return _transferByProxy(account, messageSender, totalRedeemed); } /* Once off function for SIP-60 to migrate PERI balances in the RewardEscrow contract * To the new RewardEscrowV2 contract */ function migrateEscrowBalanceToRewardEscrowV2() external onlyOwner { // Record balanceOf(RewardEscrow) contract uint rewardEscrowBalance = tokenState.balanceOf(address(rewardEscrow())); // transfer all of RewardEscrow's balance to RewardEscrowV2 // _internalTransfer emits the transfer event _internalTransfer(address(rewardEscrow()), address(rewardEscrowV2()), rewardEscrowBalance); } function setMinterRole(address _newMinter) external onlyOwner { // If address is set to zero address, mint is not prohibited minterRole = _newMinter; } function setinflationMinter(address _newinflationMinter) external onlyOwner { inflationMinter = _newinflationMinter; } // ========== EVENTS ========== event AccountLiquidated(address indexed account, uint periRedeemed, uint amountLiquidated, address liquidator); bytes32 internal constant ACCOUNTLIQUIDATED_SIG = keccak256("AccountLiquidated(address,uint256,uint256,address)"); function emitAccountLiquidated( address account, uint256 periRedeemed, uint256 amountLiquidated, address liquidator ) internal { proxy._emit( abi.encode(periRedeemed, amountLiquidated, liquidator), 2, ACCOUNTLIQUIDATED_SIG, addressToBytes32(account), 0, 0 ); } } contract PeriFinanceToEthereum is PeriFinance { address public childChainManager; constructor( address payable _proxy, TokenState _tokenState, address _owner, uint _totalSupply, address _resolver, address _minterRole, address _blacklistManager ) public PeriFinance(_proxy, _tokenState, _owner, _totalSupply, _resolver, _minterRole, _blacklistManager) {} function inflationalMint() external returns (bool) { _notImplemented(); } function issuePynthsAndStakeUSDC(uint _issueAmount, uint _usdcStakeAmount) external { _notImplemented(); } function issueMaxPynths() external { _notImplemented(); } function issuePynthsAndStakeMaxUSDC(uint _issueAmount) external { _notImplemented(); } function burnPynthsAndUnstakeUSDC(uint _burnAmount, uint _unstakeAmount) external { _notImplemented(); } function burnPynthsAndUnstakeUSDCToTarget() external { _notImplemented(); } function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived) { _notImplemented(); } function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived) { _notImplemented(); } function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived) { _notImplemented(); } function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived) { _notImplemented(); } function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualPynth vPynth) { _notImplemented(); } function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ) { _notImplemented(); } function liquidateDelinquentAccount(address account, uint pusdAmount) external returns (bool) { _notImplemented(); } function transfer(address to, uint value) external optionalProxy systemActive blacklisted(messageSender) returns (bool) { return _transferByProxy(messageSender, to, value); } function transferFrom( address from, address to, uint value ) external optionalProxy systemActive blacklisted(messageSender) blacklisted(from) returns (bool) { return _transferFromByProxy(messageSender, from, to, value); } }
Note: use public visibility so that it can be invoked in a subclass
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](6); addresses[0] = CONTRACT_PERIFINANCESTATE; addresses[1] = CONTRACT_SYSTEMSTATUS; addresses[2] = CONTRACT_EXCHANGER; addresses[3] = CONTRACT_ISSUER; addresses[4] = CONTRACT_REWARDSDISTRIBUTION; addresses[5] = CONTRACT_STAKINGSTATE_USDC; }
6,499,130
./partial_match/1/0x064774df70688825Db7D0CEcc46488A18ca7AE9F/sources/src/ERC1404TokenMinKYCv13.flattened.sol
Transfer tokens from one account to other Also manage current number of token holders Transfer will surely increase currentTotalInvestors if recipient current balance is 0
function transferSharesBetweenInvestors ( address sender, address recipient, uint256 amount, ) internal { if( ERC20.balanceOf(recipient) == 0 && recipient != Ownable.owner() ) { currentTotalInvestors = currentTotalInvestors + 1; } if( simpleTransfer == true ) { ERC20._transfer(sender, recipient, amount); ERC20.transferFrom(sender, recipient, amount); } if( ERC20.balanceOf(sender) == 0 && sender != Ownable.owner() ) { currentTotalInvestors = currentTotalInvestors - 1; } }
2,708,908
./full_match/5/0x8207B056ad080730fC048579940fD2217bFc3DC7/sources/src/Evolve.sol
Check if the claimer has the access key
function verifyClaim( address _claimer, uint256 _tokenId, uint256 _quantity ) public view override { if (_tokenId > 0) { require( balanceOf[_claimer][_tokenId] >= _quantity, "Rejected: You do not own the pre-evolved NFT(s)" ); } }
1,876,037
./full_match/1/0xa94D1052A1F67F523FCF5E7A512A43e07Cab86D7/sources/src/thirdparty/opensea/seadrop-upgradeable/src/ERC721ContractMetadataUpgradeable.sol
Reverts if the sender is not the owner or the contract itself. This function is inlined instead of being a modifier to save contract space from being inlined N times./
function _onlyOwnerOrSelf() internal view { if (_cast(msg.sender == owner()) | _cast(msg.sender == address(this)) == 0) { revert OnlyOwner(); } }
4,911,994
./full_match/42/0x6D2991198C8688261364BBC1F1740a359eBfc761/sources/browser/WETHParty.sol
[sponsored -0 , processed -1, didPass -2, cancelled -3, guildkick -4, spending -5, member -6, governance -7] Make the proposal fail if the new total number of shares and loot exceeds the limit Make the proposal fail if the new total number of shares and loot exceeds the limit
function processProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(!proposal.flags[4] && !proposal.flags[7], "not standard proposal"); bool didPass = _didPass(proposalIndex); if (totalShares.add(totalLoot).add(proposal.sharesRequested).add(proposal.lootRequested) > MAX_INPUT) { didPass = false; } if (proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken]) { didPass = false; } if (didPass) { if (members[proposal.applicant].exists) { members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested); members[proposal.applicant].loot = members[proposal.applicant].loot.add(proposal.lootRequested); members[proposal.applicant] = Member(proposal.sharesRequested, proposal.lootRequested, proposal.tributeOffered, 0, proposal.tributeOffered, 0, false, true); memberList.push(proposal.applicant); } totalLoot = totalLoot.add(proposal.lootRequested); unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered); unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested); earningsPeg += proposal.tributeOffered; earningsPeg -= proposal.paymentRequested; } _returnDeposit(); emit ProcessProposal(proposalIndex, proposalId, didPass); if (didPass) { if (members[proposal.applicant].exists) { members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested); members[proposal.applicant].loot = members[proposal.applicant].loot.add(proposal.lootRequested); members[proposal.applicant] = Member(proposal.sharesRequested, proposal.lootRequested, proposal.tributeOffered, 0, proposal.tributeOffered, 0, false, true); memberList.push(proposal.applicant); } totalLoot = totalLoot.add(proposal.lootRequested); unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered); unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested); earningsPeg += proposal.tributeOffered; earningsPeg -= proposal.paymentRequested; } _returnDeposit(); emit ProcessProposal(proposalIndex, proposalId, didPass); } else { totalShares = totalShares.add(proposal.sharesRequested); } else { unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); }
9,582,661
pragma solidity ^0.5.0; import "./ERCStaking.sol"; import "./Checkpointing.sol"; import "./res/Autopetrified.sol"; import "./res/IsContract.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; contract Staking is Autopetrified, ERCStaking, ERCStakingHistory, IsContract { using SafeMath for uint256; using Checkpointing for Checkpointing.History; using SafeERC20 for ERC20; // todo: switch back to safetransfer? // This changes all 'transfer' calls to safeTransfer string private constant ERROR_TOKEN_NOT_CONTRACT = "STAKING_TOKEN_NOT_CONTRACT"; string private constant ERROR_AMOUNT_ZERO = "STAKING_AMOUNT_ZERO"; string private constant ERROR_TOKEN_TRANSFER = "STAKING_TOKEN_TRANSFER"; string private constant ERROR_NOT_ENOUGH_BALANCE = "STAKING_NOT_ENOUGH_BALANCE"; // standard - imitates relationship between Ether and Wei uint8 private constant DECIMALS = 18; // Default minimum stake uint256 internal minStakeAmount = 0; // Default maximum stake uint256 internal maxStakeAmount = 0; // Reward tracking info uint256 internal currentClaimBlock; uint256 internal currentClaimableAmount; struct Account { Checkpointing.History stakedHistory; Checkpointing.History claimHistory; } ERC20 internal stakingToken; mapping (address => Account) internal accounts; Checkpointing.History internal totalStakedHistory; address treasuryAddress; address stakingOwnerAddress; event StakeTransferred( address indexed from, uint256 amount, address to ); event Test( uint256 test, string msg); event Claimed( address claimaint, uint256 amountClaimed ); function initialize(address _stakingToken, address _treasuryAddress) external onlyInit { require(isContract(_stakingToken), ERROR_TOKEN_NOT_CONTRACT); initialized(); stakingToken = ERC20(_stakingToken); treasuryAddress = _treasuryAddress; // Initialize claim values to zero, disabling claim prior to initial funding currentClaimBlock = 0; currentClaimableAmount = 0; // Default min stake amount is 100 AUD tokens minStakeAmount = 100 * 10**uint256(DECIMALS); // Default max stake amount is 100 million AUD tokens maxStakeAmount = 100000000 * 10**uint256(DECIMALS); } /* External functions */ /** * @notice Funds `_amount` of tokens from msg.sender into treasury stake */ function fundNewClaim(uint256 _amount) external isInitialized { // TODO: Add additional require statements here... // Stake tokens for msg.sender from treasuryAddress // Transfer tokens from msg.sender to current contract // Increase treasuryAddress stake value _stakeFor( treasuryAddress, msg.sender, _amount, bytes("")); // Update current claim information currentClaimBlock = getBlockNumber(); currentClaimableAmount = totalStakedFor(treasuryAddress); } /** * @notice Allows reward claiming for service providers */ function makeClaim() external isInitialized { require(msg.sender != treasuryAddress, "Treasury cannot claim staking reward"); require(accounts[msg.sender].stakedHistory.history.length > 0, "Stake required to claim"); require(currentClaimBlock > 0, "Claim block must be initialized"); require(currentClaimableAmount > 0, "Claimable amount must be initialized"); if (accounts[msg.sender].claimHistory.history.length > 0) { uint256 lastClaimedBlock = accounts[msg.sender].claimHistory.lastUpdated(); // Require a minimum block difference alloted to be ~1 week of blocks // Note that a new claim funding after the latest claim for this staker overrides the minimum block difference require( lastClaimedBlock < currentClaimBlock, "Minimum block difference not met"); } uint256 claimBlockTotalStake = totalStakedHistory.get(currentClaimBlock); uint256 treasuryStakeAtClaimBlock = accounts[treasuryAddress].stakedHistory.get(currentClaimBlock); uint256 claimantStakeAtClaimBlock = accounts[msg.sender].stakedHistory.get(currentClaimBlock); uint256 totalServiceProviderStakeAtClaimBlock = claimBlockTotalStake.sub(treasuryStakeAtClaimBlock); uint256 claimedValue = (claimantStakeAtClaimBlock.mul(currentClaimableAmount)).div(totalServiceProviderStakeAtClaimBlock); // Transfer value from treasury to claimant if >0 is claimed if (claimedValue > 0) { _transfer(treasuryAddress, msg.sender, claimedValue); } // Update claim history even if no value claimed accounts[msg.sender].claimHistory.add64(getBlockNumber64(), claimedValue); emit Claimed(msg.sender, claimedValue); } /** * @notice Slashes `_amount` tokens from _slashAddress * Controlled by treasury address * @param _amount Number of tokens slashed * @param _slashAddress address being slashed */ function slash(uint256 _amount, address _slashAddress) external isInitialized { // restrict functionality require(msg.sender == treasuryAddress, "Slashing functionality locked to treasury owner"); // unstaking 0 tokens is not allowed require(_amount > 0, ERROR_AMOUNT_ZERO); // transfer slashed funds to treasury address // reduce stake balance for address being slashed _transfer(_slashAddress, treasuryAddress, _amount); } /** * @notice Sets caller for stake and unstake functions * Controlled by treasury address */ function setStakingOwnerAddress(address _stakeCaller) external isInitialized { require(msg.sender == treasuryAddress, "Slashing functionality locked to treasury owner"); stakingOwnerAddress = _stakeCaller; } /** * @notice Sets the minimum stake possible * Controlled by treasury */ // NOTE that _amounts are in wei throughout function setMinStakeAmount(uint256 _amount) external isInitialized { require(msg.sender == treasuryAddress, "Stake amount manipulation limited to treasury owner"); minStakeAmount = _amount; } /** * @notice Sets the max stake possible * Controlled by treasury */ function setMaxStakeAmount(uint256 _amount) external isInitialized { require(msg.sender == treasuryAddress, "Stake amount manipulation limited to treasury owner"); maxStakeAmount = _amount; } /** * @notice Stakes `_amount` tokens, transferring them from `msg.sender` * @param _amount Number of tokens staked * @param _data Used in Staked event, to add signalling information in more complex staking applications */ function stake(uint256 _amount, bytes calldata _data) external isInitialized { require(msg.sender == stakingOwnerAddress, "Unauthorized staking operation"); _stakeFor( msg.sender, msg.sender, _amount, _data); } /** * @notice Stakes `_amount` tokens, transferring them from caller, and assigns them to `_accountAddress` * @param _accountAddress The final staker of the tokens * @param _amount Number of tokens staked * @param _data Used in Staked event, to add signalling information in more complex staking applications */ function stakeFor(address _accountAddress, uint256 _amount, bytes calldata _data) external isInitialized { require(msg.sender == stakingOwnerAddress, "Unauthorized staking operation"); _stakeFor( _accountAddress, _accountAddress, _amount, _data); } /** * @notice Unstakes `_amount` tokens, returning them to the user * @param _amount Number of tokens staked * @param _data Used in Unstaked event, to add signalling information in more complex staking applications */ function unstake(uint256 _amount, bytes calldata _data) external isInitialized { // unstaking 0 tokens is not allowed require(_amount > 0, ERROR_AMOUNT_ZERO); // checkpoint updated staking balance _modifyStakeBalance(msg.sender, _amount, false); // checkpoint total supply _modifyTotalStaked(_amount, false); // transfer tokens stakingToken.safeTransfer(msg.sender, _amount); emit Unstaked( msg.sender, _amount, totalStakedFor(msg.sender), _data); } /** * @notice Unstakes `_amount` tokens, returning them to the desired account. * @param _amount Number of tokens staked * @param _data Used in Unstaked event, to add signalling information in more complex staking applications */ function unstakeFor(address _accountAddress, uint256 _amount, bytes calldata _data) external isInitialized { require(msg.sender == stakingOwnerAddress, "Unauthorized staking operation"); // unstaking 0 tokens is not allowed require(_amount > 0, ERROR_AMOUNT_ZERO); // checkpoint updated staking balance _modifyStakeBalance(_accountAddress, _amount, false); // checkpoint total supply _modifyTotalStaked(_amount, false); // transfer tokens stakingToken.safeTransfer(_accountAddress, _amount); emit Unstaked( _accountAddress, _amount, totalStakedFor(_accountAddress), _data); } /** * @notice Get the token used by the contract for staking and locking * @return The token used by the contract for staking and locking */ function token() external view isInitialized returns (address) { return address(stakingToken); } /** * @notice Check whether it supports history of stakes * @return Always true */ function supportsHistory() external pure returns (bool) { return true; } /** * @notice Get last time `_accountAddress` modified its staked balance * @param _accountAddress Account requesting for * @return Last block number when account's balance was modified */ function lastStakedFor(address _accountAddress) external view isInitialized returns (uint256) { return accounts[_accountAddress].stakedHistory.lastUpdated(); } /** * @notice Get last time `_accountAddress` claimed a staking reward * @param _accountAddress Account requesting for * @return Last block number when claim requested */ function lastClaimedFor(address _accountAddress) external view isInitialized returns (uint256) { return accounts[_accountAddress].claimHistory.lastUpdated(); } /** * @notice Get info relating to current claim status */ function getClaimInfo() external view isInitialized returns (uint256, uint256) { return (currentClaimableAmount, currentClaimBlock); } /** * @notice Get the total amount of tokens staked by `_accountAddress` at block number `_blockNumber` * @param _accountAddress Account requesting for * @param _blockNumber Block number at which we are requesting * @return The amount of tokens staked by the account at the given block number */ function totalStakedForAt(address _accountAddress, uint256 _blockNumber) external view returns (uint256) { return accounts[_accountAddress].stakedHistory.get(_blockNumber); } /** * @notice Get the total amount of tokens staked by all users at block number `_blockNumber` * @param _blockNumber Block number at which we are requesting * @return The amount of tokens staked at the given block number */ function totalStakedAt(uint256 _blockNumber) external view returns (uint256) { return totalStakedHistory.get(_blockNumber); } /** * @notice Return the minimum stake configuration * @return min stake */ function getMinStakeAmount() external view returns (uint256) { return minStakeAmount; } /** * @notice Return the maximum stake configuration * @return max stake */ function getMaxStakeAmount() external view returns (uint256) { return maxStakeAmount; } /* Public functions */ /** * @notice Get the amount of tokens staked by `_accountAddress` * @param _accountAddress The owner of the tokens * @return The amount of tokens staked by the given account */ function totalStakedFor(address _accountAddress) public view returns (uint256) { // we assume it's not possible to stake in the future return accounts[_accountAddress].stakedHistory.getLatestValue(); } /** * @notice Get the total amount of tokens staked by all users * @return The total amount of tokens staked by all users */ function totalStaked() public view returns (uint256) { // we assume it's not possible to stake in the future return totalStakedHistory.getLatestValue(); } /* function multicall(bytes[] _calls) public { for(uint i = 0; i < _calls.length; i++) { require(address(this).delegatecall(_calls[i]), ERROR_MULTICALL_DELEGATECALL); } } */ /* Internal functions */ function _stakeFor( address _stakeAccount, address _transferAccount, uint256 _amount, bytes memory _data) internal { // staking 0 tokens is invalid require(_amount > 0, ERROR_AMOUNT_ZERO); // checkpoint updated staking balance _modifyStakeBalance(_stakeAccount, _amount, true); // checkpoint total supply _modifyTotalStaked(_amount, true); // pull tokens into Staking contract stakingToken.safeTransferFrom(_transferAccount, address(this), _amount); emit Staked( _stakeAccount, _amount, totalStakedFor(_stakeAccount), _data); } function _modifyStakeBalance(address _accountAddress, uint256 _by, bool _increase) internal { uint256 currentStake = totalStakedFor(_accountAddress); uint256 newStake; if (_increase) { newStake = currentStake.add(_by); } else { newStake = currentStake.sub(_by); } // Confirm stake is within configured bounds for non-treasury addresses if (_accountAddress != treasuryAddress) { require(newStake <= maxStakeAmount, 'Maximum stake threshold exceeded'); require(newStake > minStakeAmount || newStake == 0, 'Minimum stake threshold exceeded'); } // add new value to account history accounts[_accountAddress].stakedHistory.add64(getBlockNumber64(), newStake); } function _modifyTotalStaked(uint256 _by, bool _increase) internal { uint256 currentStake = totalStaked(); uint256 newStake; if (_increase) { newStake = currentStake.add(_by); } else { newStake = currentStake.sub(_by); } // add new value to total history totalStakedHistory.add64(getBlockNumber64(), newStake); } function _transfer(address _from, address _to, uint256 _amount) internal { // transferring 0 staked tokens is invalid require(_amount > 0, ERROR_AMOUNT_ZERO); // update stakes _modifyStakeBalance(_from, _amount, false); _modifyStakeBalance(_to, _amount, true); emit StakeTransferred(_from,_amount, _to); } }
Return the maximum stake configuration return max stake/
function getMaxStakeAmount() external view returns (uint256) { return maxStakeAmount; }
1,067,069
//Address: 0x51c340f52ecbda35f56578fb0571fb4eed064fc1 //Contract name: DragonToken //Balance: 0 Ether //Verification Date: 2/21/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @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 SafeMath * @dev Math operations with safety checks that throw on error * @dev this version copied from zeppelin-solidity, constant changed to pure */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC721Token * Generic implementation for the required functionality of the ERC721 standard */ contract ERC721Token is ERC721 { using SafeMath for uint256; // Total amount of tokens uint256 internal 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 Ownable * @dev Adds onlyOwner modifier. Subcontracts should implement checkOwner to check if caller is owner. */ contract Ownable { modifier onlyOwner() { checkOwner(); _; } function checkOwner() internal; } /** * @title OwnableImpl * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract OwnableImpl is 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 OwnableImpl() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ function checkOwner() internal { require(msg.sender == owner); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract DragonToken is OwnableImpl, ERC721Token { uint256 public price; uint256 public cap; string public name; string public symbol; function DragonToken(uint256 _price, uint256 _cap, string _name, string _symbol) public { price = _price; cap = _cap; name = _name; symbol = _symbol; } function () payable public { require(totalTokens < cap); require(msg.value >= price); _mint(msg.sender, totalTokens + 1); if (msg.value > price) { msg.sender.transfer(msg.value - price); } } function withdraw(address beneficiary, uint256 amount) onlyOwner public { beneficiary.transfer(amount); } }
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; }
15,799,297
pragma solidity 0.4.21; /** * @title DirectCrowdsaleLib * @author Modular Inc, https://modular.network * * version 3.0.0 * Copyright (c) 2017 Modular Inc * The MIT License (MIT) * https://github.com/Modular-Network/ethereum-libraries/blob/master/LICENSE * * The DirectCrowdsale Library provides functionality to create a initial coin offering * for a standard token sale with high supply where there is a direct ether to * token transfer. * * Modular provides smart contract services and security reviews for contract * deployments in addition to working on open source projects in the Ethereum * community. Our purpose is to test, document, and deploy reusable code onto the * blockchain and improve both security and usability. We also educate non-profits, * schools, and other community members about the application of blockchain * technology. For further information: modular.network * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library DirectCrowdsaleLib { using BasicMathLib for uint256; struct DirectCrowdsaleStorage { address owner; //owner of the crowdsale uint256 tokensPerEth; //number of tokens received per ether uint256 startTime; //ICO start time, timestamp uint256 endTime; //ICO end time, timestamp automatically calculated uint256 ownerBalance; //owner wei Balance uint256 startingTokenBalance; //initial amount of tokens for sale uint256[] milestoneTimes; //Array of timestamps when token price and address cap changes uint8 currentMilestone; //Pointer to the current milestone uint8 percentBurn; //percentage of extra tokens to burn bool tokensSet; //true if tokens have been prepared for crowdsale //Maps timestamp to token price mapping (uint256 => uint256) tokenPrice; //shows how much wei an address has contributed mapping (address => uint256) hasContributed; //For token withdraw function, maps a user address to the amount of tokens they can withdraw mapping (address => uint256) withdrawTokensMap; // any leftover wei that buyers contributed that didn&#39;t add up to a whole token amount mapping (address => uint256) leftoverWei; CrowdsaleToken token; //token being sold } // Indicates when an address has withdrawn their supply of tokens event LogTokensWithdrawn(address indexed _bidder, uint256 Amount); // Indicates when an address has withdrawn their supply of extra wei event LogWeiWithdrawn(address indexed _bidder, uint256 Amount); // Logs when owner has pulled eth event LogOwnerEthWithdrawn(address indexed owner, uint256 amount, string Msg); // Generic Notice message that includes and address and number event LogNoticeMsg(address _buyer, uint256 value, string Msg); // Indicates when an error has occurred in the execution of a function event LogErrorMsg(uint256 amount, string Msg); event LogTokensBought(address indexed buyer, uint256 amount); event LogTokenPriceChange(uint256 amount, string Msg); /// @dev Called by a crowdsale contract upon creation. /// @param self Stored crowdsale from crowdsale contract /// @param _owner Address of crowdsale owner /// @param _saleData Array of 2 item sets such that, in each 2 element /// set, 1 is timestamp, and 2 is price in tokens/ETH at that time /// @param _endTime Timestamp of sale end time /// @param _percentBurn Percentage of extra tokens to burn /// @param _token Token being sold function init(DirectCrowdsaleStorage storage self, address _owner, uint256[] _saleData, uint256 _endTime, uint8 _percentBurn, CrowdsaleToken _token) public { require(self.owner == 0); require(_saleData.length > 0); require((_saleData.length%2) == 0); // ensure saleData is 2-item sets require(_saleData[0] > (now + 2 hours)); require(_endTime > _saleData[0]); require(_owner > 0); require(_percentBurn <= 100); self.owner = _owner; self.startTime = _saleData[0]; self.endTime = _endTime; self.token = _token; self.percentBurn = _percentBurn; uint256 _tempTime; for(uint256 i = 0; i < _saleData.length; i += 2){ require(_saleData[i] > _tempTime); require(_saleData[i + 1] > 0); self.milestoneTimes.push(_saleData[i]); self.tokenPrice[_saleData[i]] = _saleData[i + 1]; _tempTime = _saleData[i]; } self.tokensPerEth = _saleData[1]; } /// @dev Called when an address wants to purchase tokens /// @param self Stored crowdsale from crowdsale contract /// @param _amount amount of wei that the buyer is sending /// @return true on succesful purchase function receivePurchase(DirectCrowdsaleStorage storage self, uint256 _amount) public returns (bool) { require(msg.sender != self.owner); require(validPurchase(self)); // if the token price increase interval has passed, update the current day and change the token price if ((self.milestoneTimes.length > self.currentMilestone + 1) && (now > self.milestoneTimes[self.currentMilestone + 1])) { while((self.milestoneTimes.length > self.currentMilestone + 1) && (now > self.milestoneTimes[self.currentMilestone + 1])) { self.currentMilestone += 1; } self.tokensPerEth = self.tokenPrice[self.milestoneTimes[self.currentMilestone]]; emit LogTokenPriceChange(self.tokensPerEth,"Token Price has changed!"); } uint256 _numTokens; //number of tokens that will be purchased uint256 _newBalance; //the new balance of the owner of the crowdsale uint256 _weiTokens; //temp calc holder uint256 _leftoverWei; //wei change for purchaser uint256 _remainder; //temp calc holder bool err; // Find the number of tokens as a function in wei (err,_weiTokens) = _amount.times(self.tokensPerEth); require(!err); _numTokens = _weiTokens / 1000000000000000000; _remainder = _weiTokens % 1000000000000000000; _remainder = _remainder / self.tokensPerEth; _leftoverWei += _remainder; _amount = _amount - _remainder; self.leftoverWei[msg.sender] += _leftoverWei; // can&#39;t overflow because it is under the cap self.hasContributed[msg.sender] += _amount; assert(_numTokens <= self.token.balanceOf(this)); // calculate the amount of ether in the owners balance (err,_newBalance) = self.ownerBalance.plus(_amount); require(!err); self.ownerBalance = _newBalance; // "deposit" the amount // can&#39;t overflow because it will be under the cap self.withdrawTokensMap[msg.sender] += _numTokens; //subtract tokens from owner&#39;s share (err,_remainder) = self.withdrawTokensMap[self.owner].minus(_numTokens); require(!err); self.withdrawTokensMap[self.owner] = _remainder; emit LogTokensBought(msg.sender, _numTokens); return true; } /// @dev function to set tokens for the sale /// @param self Stored Crowdsale from crowdsale contract /// @return true if tokens set successfully function setTokens(DirectCrowdsaleStorage storage self) public returns (bool) { require(msg.sender == self.owner); require(!self.tokensSet); require(now < self.endTime); uint256 _tokenBalance; _tokenBalance = self.token.balanceOf(this); self.withdrawTokensMap[msg.sender] = _tokenBalance; self.startingTokenBalance = _tokenBalance; self.tokensSet = true; return true; } /// @dev function to check if a purchase is valid /// @param self Stored crowdsale from crowdsale contract /// @return true if the transaction can buy tokens function validPurchase(DirectCrowdsaleStorage storage self) internal returns (bool) { bool nonZeroPurchase = msg.value != 0; if (crowdsaleActive(self) && nonZeroPurchase) { return true; } else { emit LogErrorMsg(msg.value, "Invalid Purchase! Check start time and amount of ether."); return false; } } /// @dev Function called by purchasers to pull tokens /// @param self Stored crowdsale from crowdsale contract /// @return true if tokens were withdrawn function withdrawTokens(DirectCrowdsaleStorage storage self) public returns (bool) { bool ok; if (self.withdrawTokensMap[msg.sender] == 0) { emit LogErrorMsg(0, "Sender has no tokens to withdraw!"); return false; } if (msg.sender == self.owner) { if(!crowdsaleEnded(self)){ emit LogErrorMsg(0, "Owner cannot withdraw extra tokens until after the sale!"); return false; } else { if(self.percentBurn > 0){ uint256 _burnAmount = (self.withdrawTokensMap[msg.sender] * self.percentBurn)/100; self.withdrawTokensMap[msg.sender] = self.withdrawTokensMap[msg.sender] - _burnAmount; ok = self.token.burnToken(_burnAmount); require(ok); } } } var total = self.withdrawTokensMap[msg.sender]; self.withdrawTokensMap[msg.sender] = 0; ok = self.token.transfer(msg.sender, total); require(ok); emit LogTokensWithdrawn(msg.sender, total); return true; } /// @dev Function called by purchasers to pull leftover wei from their purchases /// @param self Stored crowdsale from crowdsale contract /// @return true if wei was withdrawn function withdrawLeftoverWei(DirectCrowdsaleStorage storage self) public returns (bool) { if (self.leftoverWei[msg.sender] == 0) { emit LogErrorMsg(0, "Sender has no extra wei to withdraw!"); return false; } var total = self.leftoverWei[msg.sender]; self.leftoverWei[msg.sender] = 0; msg.sender.transfer(total); emit LogWeiWithdrawn(msg.sender, total); return true; } /// @dev send ether from the completed crowdsale to the owners wallet address /// @param self Stored crowdsale from crowdsale contract /// @return true if owner withdrew eth function withdrawOwnerEth(DirectCrowdsaleStorage storage self) public returns (bool) { if ((!crowdsaleEnded(self)) && (self.token.balanceOf(this)>0)) { emit LogErrorMsg(0, "Cannot withdraw owner ether until after the sale!"); return false; } require(msg.sender == self.owner); require(self.ownerBalance > 0); uint256 amount = self.ownerBalance; self.ownerBalance = 0; self.owner.transfer(amount); emit LogOwnerEthWithdrawn(msg.sender,amount,"Crowdsale owner has withdrawn all funds!"); return true; } /// @dev Gets the price and buy cap for individual addresses at the given milestone index /// @param self Stored Crowdsale from crowdsale contract /// @param timestamp Time during sale for which data is requested /// @return A 2-element array with 0 the timestamp, 1 the price in eth function getSaleData(DirectCrowdsaleStorage storage self, uint256 timestamp) public view returns (uint256[2]) { uint256[2] memory _thisData; uint256 index; while((index < self.milestoneTimes.length) && (self.milestoneTimes[index] < timestamp)) { index++; } if(index == 0) index++; _thisData[0] = self.milestoneTimes[index - 1]; _thisData[1] = self.tokenPrice[_thisData[0]]; return _thisData; } /// @dev Gets the number of tokens sold thus far /// @param self Stored Crowdsale from crowdsale contract /// @return Number of tokens sold function getTokensSold(DirectCrowdsaleStorage storage self) public view returns (uint256) { return self.startingTokenBalance - self.withdrawTokensMap[self.owner]; } /// @dev function to check if the crowdsale is currently active /// @param self Stored crowdsale from crowdsale contract /// @return success function crowdsaleActive(DirectCrowdsaleStorage storage self) public view returns (bool) { return (now >= self.startTime && now <= self.endTime); } /// @dev function to check if the crowdsale has ended /// @param self Stored crowdsale from crowdsale contract /// @return success function crowdsaleEnded(DirectCrowdsaleStorage storage self) public view returns (bool) { return now > self.endTime; } } library BasicMathLib { /// @dev Multiplies two numbers and checks for overflow before returning. /// Does not throw. /// @param a First number /// @param b Second number /// @return err False normally, or true if there is overflow /// @return res The product of a and b, or 0 if there is overflow function times(uint256 a, uint256 b) public pure returns (bool err,uint256 res) { assembly{ res := mul(a,b) switch or(iszero(b), eq(div(res,b), a)) case 0 { err := 1 res := 0 } } } /// @dev Divides two numbers but checks for 0 in the divisor first. /// Does not throw. /// @param a First number /// @param b Second number /// @return err False normally, or true if `b` is 0 /// @return res The quotient of a and b, or 0 if `b` is 0 function dividedBy(uint256 a, uint256 b) public pure returns (bool err,uint256 i) { uint256 res; assembly{ switch iszero(b) case 0 { res := div(a,b) let loc := mload(0x40) mstore(add(loc,0x20),res) i := mload(add(loc,0x20)) } default { err := 1 i := 0 } } } /// @dev Adds two numbers and checks for overflow before returning. /// Does not throw. /// @param a First number /// @param b Second number /// @return err False normally, or true if there is overflow /// @return res The sum of a and b, or 0 if there is overflow function plus(uint256 a, uint256 b) public pure returns (bool err, uint256 res) { assembly{ res := add(a,b) switch and(eq(sub(res,b), a), or(gt(res,b),eq(res,b))) case 0 { err := 1 res := 0 } } } /// @dev Subtracts two numbers and checks for underflow before returning. /// Does not throw but rather logs an Err event if there is underflow. /// @param a First number /// @param b Second number /// @return err False normally, or true if there is underflow /// @return res The difference between a and b, or 0 if there is underflow function minus(uint256 a, uint256 b) public pure returns (bool err,uint256 res) { assembly{ res := sub(a,b) switch eq(and(eq(add(res,b), a), or(lt(res,a), eq(res,a))), 1) case 0 { err := 1 res := 0 } } } } contract CrowdsaleToken { using TokenLib for TokenLib.TokenStorage; TokenLib.TokenStorage public token; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event OwnerChange(address from, address to); event Burn(address indexed burner, uint256 value); event MintingClosed(bool mintingClosed); function CrowdsaleToken(address owner, string name, string symbol, uint8 decimals, uint256 initialSupply, bool allowMinting) public { token.init(owner, name, symbol, decimals, initialSupply, allowMinting); } function name() public view returns (string) { return token.name; } function symbol() public view returns (string) { return token.symbol; } function decimals() public view returns (uint8) { return token.decimals; } function totalSupply() public view returns (uint256) { return token.totalSupply; } function initialSupply() public view returns (uint256) { return token.initialSupply; } function balanceOf(address who) public view returns (uint256) { return token.balanceOf(who); } function allowance(address owner, address spender) public view returns (uint256) { return token.allowance(owner, spender); } function transfer(address to, uint256 value) public returns (bool ok) { return token.transfer(to, value); } function transferFrom(address from, address to, uint value) public returns (bool ok) { return token.transferFrom(from, to, value); } function approve(address spender, uint256 value) public returns (bool ok) { return token.approve(spender, value); } function approveChange(address spender, uint256 valueChange, bool increase) public returns (bool) { return token.approveChange(spender, valueChange, increase); } function changeOwner(address newOwner) public returns (bool ok) { return token.changeOwner(newOwner); } function burnToken(uint256 amount) public returns (bool ok) { return token.burnToken(amount); } } pragma solidity 0.4.21; /** * @title TokenLib * @author Modular Inc, https://modular.network * * version 1.3.3 * Copyright (c) 2017 Modular, Inc * The MIT License (MIT) * https://github.com/Modular-Network/ethereum-libraries/blob/master/LICENSE * * The Token Library provides functionality to create a variety of ERC20 tokens. * See https://github.com/Modular-Network/ethereum-contracts for an example of how to * create a basic ERC20 token. * * Modular works on open source projects in the Ethereum community with the * purpose of testing, documenting, and deploying reusable code onto the * blockchain to improve security and usability of smart contracts. Modular * also strives to educate non-profits, schools, and other community members * about the application of blockchain technology. * For further information: modular.network * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library TokenLib { using BasicMathLib for uint256; struct TokenStorage { bool initialized; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string name; string symbol; uint256 totalSupply; uint256 initialSupply; address owner; uint8 decimals; bool stillMinting; } event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event OwnerChange(address from, address to); event Burn(address indexed burner, uint256 value); event MintingClosed(bool mintingClosed); /// @dev Called by the Standard Token upon creation. /// @param self Stored token from token contract /// @param _name Name of the new token /// @param _symbol Symbol of the new token /// @param _decimals Decimal places for the token represented /// @param _initial_supply The initial token supply /// @param _allowMinting True if additional tokens can be created, false otherwise function init(TokenStorage storage self, address _owner, string _name, string _symbol, uint8 _decimals, uint256 _initial_supply, bool _allowMinting) public { require(!self.initialized); self.initialized = true; self.name = _name; self.symbol = _symbol; self.totalSupply = _initial_supply; self.initialSupply = _initial_supply; self.decimals = _decimals; self.owner = _owner; self.stillMinting = _allowMinting; self.balances[_owner] = _initial_supply; } /// @dev Transfer tokens from caller&#39;s account to another account. /// @param self Stored token from token contract /// @param _to Address to send tokens /// @param _value Number of tokens to send /// @return True if completed function transfer(TokenStorage storage self, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); bool err; uint256 balance; (err,balance) = self.balances[msg.sender].minus(_value); require(!err); self.balances[msg.sender] = balance; //It&#39;s not possible to overflow token supply self.balances[_to] = self.balances[_to] + _value; emit Transfer(msg.sender, _to, _value); return true; } /// @dev Authorized caller transfers tokens from one account to another /// @param self Stored token from token contract /// @param _from Address to send tokens from /// @param _to Address to send tokens to /// @param _value Number of tokens to send /// @return True if completed function transferFrom(TokenStorage storage self, address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = self.allowed[_from][msg.sender]; bool err; uint256 balanceOwner; uint256 balanceSpender; (err,balanceOwner) = self.balances[_from].minus(_value); require(!err); (err,balanceSpender) = _allowance.minus(_value); require(!err); self.balances[_from] = balanceOwner; self.allowed[_from][msg.sender] = balanceSpender; self.balances[_to] = self.balances[_to] + _value; emit Transfer(_from, _to, _value); return true; } /// @dev Retrieve token balance for an account /// @param self Stored token from token contract /// @param _owner Address to retrieve balance of /// @return balance The number of tokens in the subject account function balanceOf(TokenStorage storage self, address _owner) public view returns (uint256 balance) { return self.balances[_owner]; } /// @dev Authorize an account to send tokens on caller&#39;s behalf /// @param self Stored token from token contract /// @param _spender Address to authorize /// @param _value Number of tokens authorized account may send /// @return True if completed function approve(TokenStorage storage self, address _spender, uint256 _value) public returns (bool) { // must set to zero before changing approval amount in accordance with spec require((_value == 0) || (self.allowed[msg.sender][_spender] == 0)); self.allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /// @dev Remaining tokens third party spender has to send /// @param self Stored token from token contract /// @param _owner Address of token holder /// @param _spender Address of authorized spender /// @return remaining Number of tokens spender has left in owner&#39;s account function allowance(TokenStorage storage self, address _owner, address _spender) public view returns (uint256 remaining) { return self.allowed[_owner][_spender]; } /// @dev Authorize third party transfer by increasing/decreasing allowed rather than setting it /// @param self Stored token from token contract /// @param _spender Address to authorize /// @param _valueChange Increase or decrease in number of tokens authorized account may send /// @param _increase True if increasing allowance, false if decreasing allowance /// @return True if completed function approveChange (TokenStorage storage self, address _spender, uint256 _valueChange, bool _increase) public returns (bool) { uint256 _newAllowed; bool err; if(_increase) { (err, _newAllowed) = self.allowed[msg.sender][_spender].plus(_valueChange); require(!err); self.allowed[msg.sender][_spender] = _newAllowed; } else { if (_valueChange > self.allowed[msg.sender][_spender]) { self.allowed[msg.sender][_spender] = 0; } else { _newAllowed = self.allowed[msg.sender][_spender] - _valueChange; self.allowed[msg.sender][_spender] = _newAllowed; } } emit Approval(msg.sender, _spender, _newAllowed); return true; } /// @dev Change owning address of the token contract, specifically for minting /// @param self Stored token from token contract /// @param _newOwner Address for the new owner /// @return True if completed function changeOwner(TokenStorage storage self, address _newOwner) public returns (bool) { require((self.owner == msg.sender) && (_newOwner > 0)); self.owner = _newOwner; emit OwnerChange(msg.sender, _newOwner); return true; } /// @dev Mints additional tokens, new tokens go to owner /// @param self Stored token from token contract /// @param _amount Number of tokens to mint /// @return True if completed function mintToken(TokenStorage storage self, uint256 _amount) public returns (bool) { require((self.owner == msg.sender) && self.stillMinting); uint256 _newAmount; bool err; (err, _newAmount) = self.totalSupply.plus(_amount); require(!err); self.totalSupply = _newAmount; self.balances[self.owner] = self.balances[self.owner] + _amount; emit Transfer(0x0, self.owner, _amount); return true; } /// @dev Permanent stops minting /// @param self Stored token from token contract /// @return True if completed function closeMint(TokenStorage storage self) public returns (bool) { require(self.owner == msg.sender); self.stillMinting = false; emit MintingClosed(true); return true; } /// @dev Permanently burn tokens /// @param self Stored token from token contract /// @param _amount Amount of tokens to burn /// @return True if completed function burnToken(TokenStorage storage self, uint256 _amount) public returns (bool) { uint256 _newBalance; bool err; (err, _newBalance) = self.balances[msg.sender].minus(_amount); require(!err); self.balances[msg.sender] = _newBalance; self.totalSupply = self.totalSupply - _amount; emit Burn(msg.sender, _amount); emit Transfer(msg.sender, 0x0, _amount); return true; } }
Called by a crowdsale contract upon creation. self Stored crowdsale from crowdsale contract _owner Address of crowdsale owner _saleData Array of 2 item sets such that, in each 2 element set, 1 is timestamp, and 2 is price in tokens/ETH at that time _endTime Timestamp of sale end time _percentBurn Percentage of extra tokens to burn _token Token being sold
function init(DirectCrowdsaleStorage storage self, address _owner, uint256[] _saleData, uint256 _endTime, uint8 _percentBurn, CrowdsaleToken _token) public { require(self.owner == 0); require(_saleData.length > 0); require(_saleData[0] > (now + 2 hours)); require(_endTime > _saleData[0]); require(_owner > 0); require(_percentBurn <= 100); self.owner = _owner; self.startTime = _saleData[0]; self.endTime = _endTime; self.token = _token; self.percentBurn = _percentBurn; uint256 _tempTime; for(uint256 i = 0; i < _saleData.length; i += 2){ require(_saleData[i] > _tempTime); require(_saleData[i + 1] > 0); self.milestoneTimes.push(_saleData[i]); self.tokenPrice[_saleData[i]] = _saleData[i + 1]; _tempTime = _saleData[i]; } self.tokensPerEth = _saleData[1]; }
7,785,704
// SPDX-License-Identifier: Unlicense pragma solidity 0.8.4; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import './BlockNoteXACL.sol'; /// @author Blockben /// @title BlockNoteX /// @notice BlockNoteX implementation contract BlockNoteX is ERC20, BlockNoteXACL { using SafeMath for uint256; constructor(address _superadmin) ERC20('BlockNoteX', 'BNOX') BlockNoteXACL(_superadmin) {} /** * Set the decimals of token to 4. */ function decimals() public view virtual override returns (uint8) { return 2; } /** * @param _to Recipient address * @param _value Value to send to the recipient from the caller account */ function transfer(address _to, uint256 _value) public override whenNotPaused returns (bool) { _transfer(_msgSender(), _to, _value); return true; } /** * @param _from Sender address * @param _to Recipient address * @param _value Value to send to the recipient from the sender account */ function transferFrom( address _from, address _to, uint256 _value ) public override whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @param _spender Spender account * @param _value Value to approve */ function approve(address _spender, uint256 _value) public override whenNotPaused returns (bool) { require((_value == 0) || (allowance(_msgSender(), _spender) == 0), 'Approve: zero first'); return super.approve(_spender, _value); } /** * @param _spender Account that allows the spending * @param _addedValue Amount which will increase the total allowance */ function increaseAllowance(address _spender, uint256 _addedValue) public override whenNotPaused returns (bool) { return super.increaseAllowance(_spender, _addedValue); } /** * @param _spender Account that allows the spending * @param _subtractValue Amount which will decrease the total allowance */ function decreaseAllowance(address _spender, uint256 _subtractValue) public override whenNotPaused returns (bool) { return super.decreaseAllowance(_spender, _subtractValue); } /** * @notice Only account with TREASURY_ADMIN is able to mint! * @param _account Mint BNOX to this account * @param _amount The mintig amount */ function mint(address _account, uint256 _amount) external onlyRole(TREASURY_ADMIN) whenNotPaused returns (bool) { _mint(_account, _amount); return true; } /** * Burn BNOX from treasury account * @notice Only account with TREASURY_ADMIN is able to burn! * @param _amount The burning amount */ function burn(uint256 _amount) external onlyRole(TREASURY_ADMIN) whenNotPaused { require(!getSourceAccountBL(treasuryAddress), 'Blacklist: treasury'); _burn(treasuryAddress, _amount); } /** * @notice Account must not be on blacklist * @param _account Mint BNOX to this account * @param _amount The minting amount */ function _mint(address _account, uint256 _amount) internal override { require(!getDestinationAccountBL(_account), 'Blacklist: target'); super._mint(_account, _amount); } /** * Transfer token between accounts, based on BNOX TOS. * - bsoFee% of the transferred amount is going to bsoPoolAddress * - generalFee% of the transferred amount is going to amountGeneral * * @param _sender The address from where the token sent * @param _recipient Recipient address * @param _amount The amount to be transferred */ function _transfer( address _sender, address _recipient, uint256 _amount ) internal override { require(!getSourceAccountBL(_sender), 'Blacklist: sender'); require(!getDestinationAccountBL(_recipient), 'Blacklist: recipient'); if ((_sender == treasuryAddress) || (_recipient == treasuryAddress)) { super._transfer(_sender, _recipient, _amount); } else { /** * Three decimal in percent. * The decimal correction is 100.000, but to avoid rounding errors, first divide by 10.000 * and after that the calculation must add 5 and divide 10 at the end. */ uint256 decimalCorrection = 10000; uint256 generalFeePercent256 = generalFee; uint256 bsoFeePercent256 = bsoFee; uint256 totalFeePercent = generalFeePercent256.add(bsoFeePercent256); uint256 totalFeeAmount = _amount.mul(totalFeePercent).div(decimalCorrection).add(5).div(10); uint256 amountBso = _amount.mul(bsoFeePercent256).div(decimalCorrection).add(5).div(10); uint256 amountGeneral = totalFeeAmount.sub(amountBso); uint256 recipientTransferAmount = _amount.sub(totalFeeAmount); super._transfer(_sender, _recipient, recipientTransferAmount); if (amountGeneral > 0) { super._transfer(_sender, feeAddress, amountGeneral); } if (amountBso > 0) { super._transfer(_sender, bsoPoolAddress, amountBso); } } } } // SPDX-License-Identifier: Unlicense pragma solidity 0.8.4; import '@openzeppelin/contracts/security/Pausable.sol'; import '@openzeppelin/contracts/access/AccessControl.sol'; import '@openzeppelin/contracts/utils/Context.sol'; abstract contract BlockNoteXACL is Pausable, AccessControl { /// @notice TOKEN_ADMIN bytes32 public constant TOKEN_ADMIN = keccak256('TOKEN_ADMIN'); /// @notice TREASURY_ADMIN. Treasury admins can only mint or burn bytes32 public constant TREASURY_ADMIN = keccak256('TREASURY_ADMIN'); /// @notice AML_ADMIN. AML Admins can only whitelist and blacklist addresses bytes32 public constant AML_ADMIN = keccak256('AML_ADMIN'); /** * @notice superadmin on paper wallet for worst case compromise */ address superadmin; mapping(address => bool) sourceAccountBL; mapping(address => bool) destinationAccountBL; /** * @notice Public URL, that contains detailed up-to-date information about the token. */ string public url; address public treasuryAddress; address public feeAddress; address public bsoPoolAddress; uint16 public generalFee; uint16 public bsoFee; event BNOXSourceAccountBL(address indexed _account, bool _lockValue); event BNOXDestinationAccountBL(address indexed _account, bool _lockValue); event BNOXUrlSet(string url); event BNOXTreasuryAddressChange(address _newAddress); event BNOXFeeAddressChange(address _newAddress); event BNOXBsoPoolAddressChange(address _newAddress); event BNOXGeneralFeeChange(uint256 _newFee); event BNOXBsoFeeChange(uint256 _newFee); // Setting the superadmin and adding the deployer as admin constructor(address _superadmin) { require(_superadmin != address(0), '_superadmin cannot be 0'); superadmin = _superadmin; _setRoleAdmin(TOKEN_ADMIN, TOKEN_ADMIN); _setRoleAdmin(TREASURY_ADMIN, TOKEN_ADMIN); _setRoleAdmin(AML_ADMIN, TOKEN_ADMIN); _setupRole(TOKEN_ADMIN, _superadmin); _setupRole(TREASURY_ADMIN, _superadmin); _setupRole(AML_ADMIN, _superadmin); _setupRole(TOKEN_ADMIN, _msgSender()); } /** * @notice Override for AccessControl.sol revokeRole to prevent revoke against superadmin * @param _role The role which * @param _account Revokes role from the account */ function revokeRole(bytes32 _role, address _account) public virtual override onlyRole(getRoleAdmin(_role)) { require(_account != superadmin, 'superadmin can not be changed'); super.revokeRole(_role, _account); } function getSourceAccountBL(address _account) public view returns (bool) { return sourceAccountBL[_account]; } function getDestinationAccountBL(address _account) public view returns (bool) { return destinationAccountBL[_account]; } function setSourceAccountBL(address _account, bool _lockValue) external onlyRole(AML_ADMIN) { sourceAccountBL[_account] = _lockValue; emit BNOXSourceAccountBL(_account, _lockValue); } function setBatchSourceAccountBL(address[] calldata _addresses, bool _lockValue) external onlyRole(AML_ADMIN) { require(_addresses.length <= 200, 'Batch: too many addresses'); for (uint256 i = 0; i < _addresses.length; i++) { sourceAccountBL[_addresses[i]] = _lockValue; } } function setBatchDestinationAccountBL(address[] calldata _addresses, bool _lockValue) external onlyRole(AML_ADMIN) { require(_addresses.length <= 200, 'Batch: too many addresses'); for (uint256 i = 0; i < _addresses.length; i++) { destinationAccountBL[_addresses[i]] = _lockValue; } } function setDestinationAccountBL(address _account, bool _lockValue) external onlyRole(AML_ADMIN) { destinationAccountBL[_account] = _lockValue; emit BNOXDestinationAccountBL(_account, _lockValue); } function setUrl(string calldata _newUrl) external onlyRole(TOKEN_ADMIN) { url = _newUrl; emit BNOXUrlSet(_newUrl); } function setTreasuryAddress(address _newAddress) external onlyRole(TOKEN_ADMIN) { require(_newAddress != address(0), 'treasury address cannot be 0'); treasuryAddress = _newAddress; emit BNOXTreasuryAddressChange(_newAddress); } function setFeeAddress(address _newAddress) external onlyRole(TOKEN_ADMIN) { require(_newAddress != address(0), 'fee address cannot be 0'); feeAddress = _newAddress; emit BNOXFeeAddressChange(_newAddress); } function setBsoPoolAddress(address _newAddress) external onlyRole(TOKEN_ADMIN) { require(_newAddress != address(0), 'bso pool address cannot be 0'); bsoPoolAddress = _newAddress; emit BNOXBsoPoolAddressChange(_newAddress); } function setGeneralFee(uint16 _newFee) external onlyRole(TOKEN_ADMIN) { generalFee = _newFee; emit BNOXGeneralFeeChange(_newFee); } function setBsoFee(uint16 _newFee) external onlyRole(TOKEN_ADMIN) { bsoFee = _newFee; emit BNOXBsoFeeChange(_newFee); } function pause() external onlyRole(TOKEN_ADMIN) { _pause(); } function unpause() external onlyRole(TOKEN_ADMIN) { _unpause(); } } // SPDX-License-Identifier: MIT 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 no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
_spender Spender account _value Value to approve/
function approve(address _spender, uint256 _value) public override whenNotPaused returns (bool) { require((_value == 0) || (allowance(_msgSender(), _spender) == 0), 'Approve: zero first'); return super.approve(_spender, _value); }
1,818,390
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract HODLPigs is ERC721, Pausable, Ownable, ERC721Enumerable { // Contract by Raid55 for HODLPIGS // HODLPIGS.com, worlds first NFT Ether Piggy Banks // Coded with constant and absolute dreed that I made a big mistake somewhere. // you can't get me int overflow hackers lmao using SafeMath for uint256; // Total ledger (from deposits, PigId -> eth) mapping(uint256 => uint256) public ledger; uint256 public totalLedger; // Price per pig uint256 public constant PIG_PRICE = 0.05 ether; //0.05 // Max pig purchased in one Tx uint256 public constant MAX_PER_TX = 20; // total supply of pigs to be minted uint256 public constant ORIGINAL_SUPPLY = 10000; // timestamp when the index should get set // if token did not sell out by then uint256 public constant REVEAL_TIMESTAMP = 1635145200; // a hash of all the images hashed in it's // original generated sequence string public provenance = "75804417186d360a948d7734e3273fd210c60a3968ff9a83201439d9deb11270"; // mint index that increments to 9999 // prevents and mints after that uint256 public mintIdx = 0; // base uri that points to IPFS string public baseURI = "https://hodlpigs.com/public/pig/"; // random block choosen to get starting index from uint256 public startingIndexBlock; // Random offset to keep sale random uint256 public startingIndex; // Locks URI of contract bool public locked = false; // Events event Deposit(address indexed from, uint256 indexed tokenId, uint256 value); event Cracked( address indexed owner, uint256 indexed tokenId, uint256 value ); constructor() ERC721("HODLPIGS", "HDPIGS") { reservePigs(); pause(); } /* * deposit money into a pig's ledger */ function deposit(uint256 tokenId) public payable { //check if pig exists require(_exists(tokenId), "Pig has been cracked or is not minted"); ledger[tokenId] = ledger[tokenId].add(msg.value); totalLedger = totalLedger.add(msg.value); emit Deposit(msg.sender, tokenId, msg.value); } /* * Cracks pig, burning the NFT using the_burn command * sends the money the pig had in the ledger to the caller (pig owner) */ function crackPig(uint256 tokenId) public { require(_exists(tokenId), "Pig has been cracked or is not minted"); // require that the sender owns the token require( ownerOf(tokenId) == msg.sender, "Only owner can crack open a pig" ); require(ledger[tokenId] > 0, "Pig is empty"); // subtract balance uint256 balance = ledger[tokenId]; ledger[tokenId] = 0; totalLedger = totalLedger.sub(balance); // scary stuff _burn(tokenId); // you can't get me re-entrency hackers lmao xd payable(msg.sender).transfer(balance); emit Cracked(msg.sender, tokenId, balance); } /* * mint pig, set starting index if last pig or past reveal */ function mintPig(uint256 numberOfTokens) public payable whenNotPaused { require(numberOfTokens <= MAX_PER_TX, "Max of 10 tokens per transaction"); require( mintIdx + numberOfTokens <= ORIGINAL_SUPPLY, "Purchase would exceed max supply" ); require( msg.value >= numberOfTokens * PIG_PRICE, "Insuficient Ether Provided" ); for (uint256 i = 0; i < numberOfTokens; i++) { if (mintIdx < ORIGINAL_SUPPLY) { _safeMint(msg.sender, mintIdx); mintIdx += 1; } } // If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after // the end of pre-sale, set the starting index block if ( startingIndexBlock == 0 && (mintIdx == ORIGINAL_SUPPLY.sub(1) || block.timestamp >= REVEAL_TIMESTAMP) ) { startingIndexBlock = block.number; } } /* * to be called after final URI is set to freeze metadata */ function freeze() public onlyOwner { require(!locked, "Contract already locked"); locked = true; } /* * to set the final URI once reveal is done */ function setBaseURI(string memory newURI) public onlyOwner { require(!locked, "Contract is locked"); baseURI = newURI; } /* * just in case prov needs to be reset */ function setProvenance(string memory newProv) public onlyOwner { require(!locked, "Contract is locked"); provenance = newProv; } /* * Our own pigs for givaway, friends, and family */ function reservePigs() public onlyOwner { require(mintIdx == 0, "can only reserve first 30 pigs"); for (uint256 i = 0; i < 50; i++) { _safeMint(msg.sender, mintIdx); mintIdx += 1; } } /* * Drains smart contract wallet without * withdrawing the ledger funds */ function drain() public onlyOwner { uint256 drainable = address(this).balance; drainable = drainable.sub(totalLedger); payable(msg.sender).transfer(drainable); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } /* * Set starting index after starting block has been picked. */ function setStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint256(blockhash(startingIndexBlock)) % ORIGINAL_SUPPLY; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint256(blockhash(block.number - 1)) % ORIGINAL_SUPPLY; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * Set the starting index block for the collection, essentially unblocking * setting starting index, i dont know why its here but here it is */ function emergencySetStartingIndexBlock() public onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } function _baseURI() internal view override returns (string memory) { return baseURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) whenNotPaused { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT 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 no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @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(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^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.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); }
just in case prov needs to be reset/
function setProvenance(string memory newProv) public onlyOwner { require(!locked, "Contract is locked"); provenance = newProv; }
323,737
/** * Copyright (C) 2017-2018 Hashfuture Inc. All rights reserved. */ pragma solidity ^0.4.22; library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice&#39;s text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } } contract owned { address public holder; constructor() public { holder = msg.sender; } modifier onlyHolder { require(msg.sender == holder, "This func only can be calle by holder"); _; } } contract asset is owned { using strings for *; /*Asset Struct*/ struct data { //link URL of the original information for storing data // null means undisclosed string link; //The encryption method of the original data, such as SHA-256 string encryptionType; //Hash value string hashValue; } data[] dataArray; uint dataNum; //The validity of the contract bool public isValid; //The init status bool public isInit; //The tradeable status of asset bool public isTradeable; uint public price; //Some notes string public remark1; //Other notes, holder can be written //Reservations for validation functions string public remark2; /** constructor */ constructor() public { isValid = true; isInit = false; isTradeable = false; price = 0; dataNum = 0; } /** * Initialize a new asset * @param dataNumber The number of data array * @param linkSet The set of URL of the original information for storing data, if null means undisclosed * needle is " " * @param encryptionTypeSet The set of encryption method of the original data, such as SHA-256 * needle is " " * @param hashValueSet The set of hashvalue * needle is " " */ function initAsset( uint dataNumber, string linkSet, string encryptionTypeSet, string hashValueSet) public onlyHolder { // split string to array var links = linkSet.toSlice(); var encryptionTypes = encryptionTypeSet.toSlice(); var hashValues = hashValueSet.toSlice(); var delim = " ".toSlice(); dataNum = dataNumber; // after init, the initAsset function cannot be called require(isInit == false, "The contract has been initialized"); //check data require(dataNumber >= 1, "The dataNumber should bigger than 1"); require(dataNumber - 1 == links.count(delim), "The uumber of linkSet error"); require(dataNumber - 1 == encryptionTypes.count(delim), "The uumber of encryptionTypeSet error"); require(dataNumber - 1 == hashValues.count(delim), "The uumber of hashValues error"); isInit = true; var empty = "".toSlice(); for (uint i = 0; i < dataNumber; i++) { var link = links.split(delim); var encryptionType = encryptionTypes.split(delim); var hashValue = hashValues.split(delim); //require data not null // link can be empty require(!encryptionType.empty(), "The encryptionTypeSet data error"); require(!hashValue.empty(), "The hashValues data error"); dataArray.push( data(link.toString(), encryptionType.toString(), hashValue.toString()) ); } } /** * Get base asset info */ function getAssetBaseInfo() public view returns (uint _price, bool _isTradeable, uint _dataNum, string _remark1, string _remark2) { require(isValid == true, "contract is invaild"); _price = price; _isTradeable = isTradeable; _dataNum = dataNum; _remark1 = remark1; _remark2 = remark2; } /** * Get data info by index * @param index index of dataArray */ function getDataByIndex(uint index) public view returns (string link, string encryptionType, string hashValue) { require(isValid == true, "contract is invaild"); require(index >= 0, "The idx smaller than 0"); require(index < dataNum, "The idx bigger than dataNum"); link = dataArray[index].link; encryptionType = dataArray[index].encryptionType; hashValue = dataArray[index].hashValue; } /** * set the price of asset * @param newPrice price of asset * Only can be called by holder */ function setPrice(uint newPrice) public onlyHolder { require(isValid == true, "contract is invaild"); price = newPrice; } /** * set the tradeable status of asset * @param status status of isTradeable * Only can be called by holder */ function setTradeable(bool status) public onlyHolder { require(isValid == true, "contract is invaild"); isTradeable = status; } /** * set the remark1 * @param content new content of remark1 * Only can be called by holder */ function setRemark1(string content) public onlyHolder { require(isValid == true, "contract is invaild"); remark1 = content; } /** * set the remark2 * @param content new content of remark2 * Only can be called by holder */ function setRemark2(string content) public onlyHolder { require(isValid == true, "contract is invaild"); remark2 = content; } /** * Modify the link of the indexth data to be url * @param index index of assetInfo * @param url new link * Only can be called by holder */ function setDataLink(uint index, string url) public onlyHolder { require(isValid == true, "contract is invaild"); require(index >= 0, "The index smaller than 0"); require(index < dataNum, "The index bigger than dataNum"); dataArray[index].link = url; } /** * cancel contract * Only can be called by holder */ function cancelContract() public onlyHolder { isValid = false; } /** * Get the number of assetInfo */ function getDataNum() public view returns (uint num) { num = dataNum; } /** * Transfer holder */ function transferOwnership(address newHolder, bool status) public onlyHolder { holder = newHolder; isTradeable = status; } }
cancel contract Only can be called by holder/
function cancelContract() public onlyHolder { isValid = false; }
2,098,175
pragma solidity >=0.5.4 <0.6.0; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } interface INameTAOPosition { function senderIsAdvocate(address _sender, address _id) external view returns (bool); function senderIsListener(address _sender, address _id) external view returns (bool); function senderIsSpeaker(address _sender, address _id) external view returns (bool); function senderIsPosition(address _sender, address _id) external view returns (bool); function getAdvocate(address _id) external view returns (address); function nameIsAdvocate(address _nameId, address _id) external view returns (bool); function nameIsPosition(address _nameId, address _id) external view returns (bool); function initialize(address _id, address _advocateId, address _listenerId, address _speakerId) external returns (bool); function determinePosition(address _sender, address _id) external view returns (uint256); } interface IAOSetting { function getSettingValuesByTAOName(address _taoId, string calldata _settingName) external view returns (uint256, bool, address, bytes32, string memory); function getSettingTypes() external view returns (uint8, uint8, uint8, uint8, uint8); function settingTypeLookup(uint256 _settingId) external view returns (uint8); } interface INamePublicKey { function initialize(address _id, address _defaultKey, address _writerKey) external returns (bool); function isKeyExist(address _id, address _key) external view returns (bool); function getDefaultKey(address _id) external view returns (address); function whitelistAddKey(address _id, address _key) external returns (bool); } interface INameFactory { function nonces(address _nameId) external view returns (uint256); function incrementNonce(address _nameId) external returns (uint256); function ethAddressToNameId(address _ethAddress) external view returns (address); function setNameNewAddress(address _id, address _newAddress) external returns (bool); function nameIdToEthAddress(address _nameId) external view returns (address); } interface INameAccountRecovery { function isCompromised(address _id) external view returns (bool); } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string memory tokenName, string memory tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != address(0)); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply 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); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } /** * @title TAO */ contract TAO { using SafeMath for uint256; address public vaultAddress; string public name; // the name for this TAO address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address // TAO's data string public datHash; string public database; string public keyValue; bytes32 public contentId; /** * 0 = TAO * 1 = Name */ uint8 public typeId; /** * @dev Constructor function */ constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress ) public { name = _name; originId = _originId; datHash = _datHash; database = _database; keyValue = _keyValue; contentId = _contentId; // Creating TAO typeId = 0; vaultAddress = _vaultAddress; } /** * @dev Checks if calling address is Vault contract */ modifier onlyVault { require (msg.sender == vaultAddress); _; } /** * Will receive any ETH sent */ function () external payable { } /** * @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient` * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferEth(address payable _recipient, uint256 _amount) public onlyVault returns (bool) { _recipient.transfer(_amount); return true; } /** * @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient` * @param _erc20TokenAddress The address of ERC20 Token * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) { TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress); _erc20.transfer(_recipient, _amount); return true; } } /** * @title Name */ contract Name is TAO { /** * @dev Constructor function */ constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress) TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public { // Creating Name typeId = 1; } } /** * @title AOLibrary */ library AOLibrary { using SafeMath for uint256; uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1 uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000 /** * @dev Check whether or not the given TAO ID is a TAO * @param _taoId The ID of the TAO * @return true if yes. false otherwise */ function isTAO(address _taoId) public view returns (bool) { return (_taoId != address(0) && bytes(TAO(address(uint160(_taoId))).name()).length > 0 && TAO(address(uint160(_taoId))).originId() != address(0) && TAO(address(uint160(_taoId))).typeId() == 0); } /** * @dev Check whether or not the given Name ID is a Name * @param _nameId The ID of the Name * @return true if yes. false otherwise */ function isName(address _nameId) public view returns (bool) { return (_nameId != address(0) && bytes(TAO(address(uint160(_nameId))).name()).length > 0 && Name(address(uint160(_nameId))).originId() != address(0) && Name(address(uint160(_nameId))).typeId() == 1); } /** * @dev Check if `_tokenAddress` is a valid ERC20 Token address * @param _tokenAddress The ERC20 Token address to check */ function isValidERC20TokenAddress(address _tokenAddress) public view returns (bool) { if (_tokenAddress == address(0)) { return false; } TokenERC20 _erc20 = TokenERC20(_tokenAddress); return (_erc20.totalSupply() >= 0 && bytes(_erc20.name()).length > 0 && bytes(_erc20.symbol()).length > 0); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate * @param _sender The address to check * @param _theAO The AO address * @param _nameTAOPositionAddress The address of NameTAOPosition * @return true if yes, false otherwise */ function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) { return (_sender == _theAO || ( (isTAO(_theAO) || isName(_theAO)) && _nameTAOPositionAddress != address(0) && INameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO) ) ); } /** * @dev Return the divisor used to correctly calculate percentage. * Percentage stored throughout AO contracts covers 4 decimals, * so 1% is 10000, 1.25% is 12500, etc */ function PERCENTAGE_DIVISOR() public pure returns (uint256) { return _PERCENTAGE_DIVISOR; } /** * @dev Return the divisor used to correctly calculate multiplier. * Multiplier stored throughout AO contracts covers 6 decimals, * so 1 is 1000000, 0.023 is 23000, etc */ function MULTIPLIER_DIVISOR() public pure returns (uint256) { return _MULTIPLIER_DIVISOR; } /** * @dev deploy a TAO * @param _name The name of the TAO * @param _originId The Name ID the creates the TAO * @param _datHash The datHash of this TAO * @param _database The database for this TAO * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this TAO * @param _nameTAOVaultAddress The address of NameTAOVault */ function deployTAO(string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _nameTAOVaultAddress ) public returns (TAO _tao) { _tao = new TAO(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress); } /** * @dev deploy a Name * @param _name The name of the Name * @param _originId The eth address the creates the Name * @param _datHash The datHash of this Name * @param _database The database for this Name * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this Name * @param _nameTAOVaultAddress The address of NameTAOVault */ function deployName(string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _nameTAOVaultAddress ) public returns (Name _myName) { _myName = new Name(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress); } /** * @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier` * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _currentPrimordialBalance Account's current primordial ion balance * @param _additionalWeightedMultiplier The weighted multiplier to be added * @param _additionalPrimordialAmount The primordial ion amount to be added * @return the new primordial weighted multiplier */ function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { if (_currentWeightedMultiplier > 0) { uint256 _totalWeightedIons = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount)); uint256 _totalIons = _currentPrimordialBalance.add(_additionalPrimordialAmount); return _totalWeightedIons.div(_totalIons); } else { return _additionalWeightedMultiplier; } } /** * @dev Calculate the primordial ion multiplier on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Multiplier = S * Ending Multiplier = E * To Purchase = P * Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E) * * @param _purchaseAmount The amount of primordial ion intended to be purchased * @param _totalPrimordialMintable Total Primordial ion mintable * @param _totalPrimordialMinted Total Primordial ion minted so far * @param _startingMultiplier The starting multiplier in (10 ** 6) * @param _endingMultiplier The ending multiplier in (10 ** 6) * @return The multiplier in (10 ** 6) */ function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * Multiplier = (1 - (temp / T)) x (S-E) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals * so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E) * Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR * Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR * Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation * Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E) */ uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)); /** * Since _startingMultiplier and _endingMultiplier are in 6 decimals * Need to divide multiplier by _MULTIPLIER_DIVISOR */ return multiplier.div(_MULTIPLIER_DIVISOR); } else { return 0; } } /** * @dev Calculate the bonus percentage of network ion on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Network Bonus Multiplier = Bs * Ending Network Bonus Multiplier = Be * To Purchase = P * AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be) * * @param _purchaseAmount The amount of primordial ion intended to be purchased * @param _totalPrimordialMintable Total Primordial ion intable * @param _totalPrimordialMinted Total Primordial ion minted so far * @param _startingMultiplier The starting Network ion bonus multiplier * @param _endingMultiplier The ending Network ion bonus multiplier * @return The bonus percentage */ function calculateNetworkBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * B% = (1 - (temp / T)) x (Bs-Be) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals * so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be) * B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR * B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR * Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) * But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR */ uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR); return bonusPercentage; } else { return 0; } } /** * @dev Calculate the bonus amount of network ion on a given lot * AO Bonus Amount = B% x P * * @param _purchaseAmount The amount of primordial ion intended to be purchased * @param _totalPrimordialMintable Total Primordial ion intable * @param _totalPrimordialMinted Total Primordial ion minted so far * @param _startingMultiplier The starting Network ion bonus multiplier * @param _endingMultiplier The ending Network ion bonus multiplier * @return The bonus percentage */ function calculateNetworkBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { uint256 bonusPercentage = calculateNetworkBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier); /** * Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR * when calculating the network ion bonus amount */ uint256 networkBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR); return networkBonus; } /** * @dev Calculate the maximum amount of Primordial an account can burn * _primordialBalance = P * _currentWeightedMultiplier = M * _maximumMultiplier = S * _amountToBurn = B * B = ((S x P) - (P x M)) / S * * @param _primordialBalance Account's primordial ion balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _maximumMultiplier The maximum multiplier of this account * @return The maximum burn amount */ function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) { return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier); } /** * @dev Calculate the new multiplier after burning primordial ion * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToBurn = B * _newMultiplier = E * E = (P x M) / (P - B) * * @param _primordialBalance Account's primordial ion balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToBurn The amount of primordial ion to burn * @return The new multiplier */ function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn)); } /** * @dev Calculate the new multiplier after converting network ion to primordial ion * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToConvert = C * _newMultiplier = E * E = (P x M) / (P + C) * * @param _primordialBalance Account's primordial ion balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToConvert The amount of network ion to convert * @return The new multiplier */ function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert)); } /** * @dev count num of digits * @param number uint256 of the nuumber to be checked * @return uint8 num of digits */ function numDigits(uint256 number) public pure returns (uint8) { uint8 digits = 0; while(number != 0) { number = number.div(10); digits++; } return digits; } } contract TheAO { address public theAO; address public nameTAOPositionAddress; // Check whether an address is whitelisted and granted access to transact // on behalf of others mapping (address => bool) public whitelist; constructor() public { theAO = msg.sender; } /** * @dev Checks if msg.sender is in whitelist. */ modifier inWhitelist() { require (whitelist[msg.sender] == true); _; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public { require (msg.sender == theAO); require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public { require (msg.sender == theAO); require (_account != address(0)); whitelist[_account] = _whitelist; } } /** * @title NameAccountRecovery */ contract NameAccountRecovery is TheAO { using SafeMath for uint256; address public settingTAOId; address public nameFactoryAddress; address public nameTAOPositionAddress; address public namePublicKeyAddress; address public aoSettingAddress; INameFactory internal _nameFactory; INameTAOPosition internal _nameTAOPosition; INamePublicKey internal _namePublicKey; IAOSetting internal _aoSetting; struct AccountRecovery { // If submitted, then Name is locked until lockedUntilTimestamp // and if no action is taken by the Speaker, then the current // eth address associated with the Name can resume operation bool submitted; uint256 submittedTimestamp; // Timestamp when this account recovery is submitted uint256 lockedUntilTimestamp; // The deadline for the current Speaker of Name to respond and replace the new eth address } mapping (address => AccountRecovery) internal accountRecoveries; // Event to be broadcasted to public when current Listener of Name submitted account recovery for a Name event SubmitAccountRecovery(address indexed nameId, address listenerId, bool compromised, uint256 submittedTimestamp, uint256 lockedUntilTimestamp, uint256 nonce); // Event to be broadcasted to public when current Speaker of Name set new ETH Address for a Name event SetNameNewAddress(address indexed nameId, address speakerId, address newAddress, uint256 timestamp, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { setNameFactoryAddress(_nameFactoryAddress); setNameTAOPositionAddress(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the NameFactory Address * @param _nameFactoryAddress The address of NameFactory */ function setNameFactoryAddress(address _nameFactoryAddress) public onlyTheAO { require (_nameFactoryAddress != address(0)); nameFactoryAddress = _nameFactoryAddress; _nameFactory = INameFactory(_nameFactoryAddress); } /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = INameTAOPosition(_nameTAOPositionAddress); } /** * @dev The AO set the NamePublicKey Address * @param _namePublicKeyAddress The address of NamePublicKey */ function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO { require (_namePublicKeyAddress != address(0)); namePublicKeyAddress = _namePublicKeyAddress; _namePublicKey = INamePublicKey(_namePublicKeyAddress); } /** * @dev The AO sets setting TAO ID * @param _settingTAOId The new setting TAO ID to set */ function setSettingTAOId(address _settingTAOId) public onlyTheAO { require (AOLibrary.isTAO(_settingTAOId)); settingTAOId = _settingTAOId; } /** * @dev The AO sets AO Setting address * @param _aoSettingAddress The address of AOSetting */ function setAOSettingAddress(address _aoSettingAddress) public onlyTheAO { require (_aoSettingAddress != address(0)); aoSettingAddress = _aoSettingAddress; _aoSetting = IAOSetting(_aoSettingAddress); } /***** PUBLIC METHODS *****/ /** * @dev Get AccountRecovery information given a Name ID * @param _id The ID of the Name * @return the submit status of the account recovery * @return submittedTimestamp - Timestamp when this account recovery is submitted * @return lockedUntilTimestamp - The deadline for the current Speaker of Name to respond and replace the new eth address */ function getAccountRecovery(address _id) public isName(_id) view returns (bool, uint256, uint256) { AccountRecovery memory _accountRecovery = accountRecoveries[_id]; return ( _accountRecovery.submitted, _accountRecovery.submittedTimestamp, _accountRecovery.lockedUntilTimestamp ); } /** * @dev Listener of Name submits an account recovery for the Name * @param _id The ID of the Name */ function submitAccountRecovery(address _id) public isName(_id) senderIsName { require (_nameTAOPosition.senderIsListener(msg.sender, _id)); // Can't submit account recovery for itself require (!_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); // Make sure Listener is not currenty compromised require (!this.isCompromised(_nameFactory.ethAddressToNameId(msg.sender))); AccountRecovery storage _accountRecovery = accountRecoveries[_id]; // Make sure currently it's not currently locked require (now > _accountRecovery.lockedUntilTimestamp); _accountRecovery.submitted = true; _accountRecovery.submittedTimestamp = now; _accountRecovery.lockedUntilTimestamp = _accountRecovery.submittedTimestamp.add(_getAccountRecoveryLockDuration()); uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit SubmitAccountRecovery(_id, _nameFactory.ethAddressToNameId(msg.sender), true, _accountRecovery.submittedTimestamp, _accountRecovery.lockedUntilTimestamp, _nonce); } /** * @dev Check whether or not current Name is compromised, * i.e an account recovery has been submitted and waiting for * action from Speaker * @param _id The ID of the Name * @return true if yes. false otherwise */ function isCompromised(address _id) external isName(_id) view returns (bool) { AccountRecovery memory _accountRecovery = accountRecoveries[_id]; return (_accountRecovery.submitted && now <= _accountRecovery.lockedUntilTimestamp); } /** * @dev Speaker of Name respond to AccountRecovery and submits a new eth address for Name * @param _id The ID of the Name * @param _newAddress The new replacement eth address */ function setNameNewAddress(address _id, address _newAddress) public isName(_id) senderIsName { require (_newAddress != address(0)); // Only Speaker can do this action require (_nameTAOPosition.senderIsSpeaker(msg.sender, _id)); // Make sure Speaker is not currenty compromised require (!this.isCompromised(_nameFactory.ethAddressToNameId(msg.sender))); // Make sure this Name is currently compromised and needs action require (this.isCompromised(_id)); // Make sure the newAddress is not yet assigned to a Name require (_nameFactory.ethAddressToNameId(_newAddress) == address(0)); AccountRecovery storage _accountRecovery = accountRecoveries[_id]; _accountRecovery.submitted = false; _accountRecovery.submittedTimestamp = 0; _accountRecovery.lockedUntilTimestamp = 0; // Replace the existing eth address with new address require (_nameFactory.setNameNewAddress(_id, _newAddress)); // Add this _newAddress to Name's publicKey if needed if (!_namePublicKey.isKeyExist(_id, _newAddress)) { require (_namePublicKey.whitelistAddKey(_id, _newAddress)); } uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit SetNameNewAddress(_id, _nameFactory.ethAddressToNameId(msg.sender), _newAddress, now, 1); } /***** INTERNAL METHOD *****/ /** * @dev Get accountRecoveryLockDuration setting * @return accountRecoveryLockDuration = The amount of time for current Speaker of Name to response and replace the eth address associated with the Name */ function _getAccountRecoveryLockDuration() internal view returns (uint256) { (uint256 accountRecoveryLockDuration,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'accountRecoveryLockDuration'); return accountRecoveryLockDuration; } }
PUBLIC METHODS / Get AccountRecovery information given a Name ID _id The ID of the Name return the submit status of the account recovery return submittedTimestamp - Timestamp when this account recovery is submitted return lockedUntilTimestamp - The deadline for the current Speaker of Name to respond and replace the new eth address/
function getAccountRecovery(address _id) public isName(_id) view returns (bool, uint256, uint256) { AccountRecovery memory _accountRecovery = accountRecoveries[_id]; return ( _accountRecovery.submitted, _accountRecovery.submittedTimestamp, _accountRecovery.lockedUntilTimestamp ); }
12,678,642
// File: contracts/interfaces/IMarketHandler.sol pragma solidity 0.6.12; /** * @title BiFi's market handler interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketHandler { function setCircuitBreaker(bool _emergency) external returns (bool); function setCircuitBreakWithOwner(bool _emergency) external returns (bool); function getTokenName() external view returns (string memory); function ownershipTransfer(address payable newOwner) external returns (bool); function deposit(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool); function withdraw(uint256 unifiedTokenAmount, bool allFlag) external returns (bool); function borrow(uint256 unifiedTokenAmount, bool allFlag) external returns (bool); function repay(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool); function executeFlashloan( address receiverAddress, uint256 amount ) external returns (bool); function depositFlashloanFee( uint256 amount ) external returns (bool); function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external view returns (uint256); function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) external returns (uint256, uint256, uint256); function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) external returns (uint256); function getTokenHandlerLimit() external view returns (uint256, uint256); function getTokenHandlerBorrowLimit() external view returns (uint256); function getTokenHandlerMarginCallLimit() external view returns (uint256); function setTokenHandlerBorrowLimit(uint256 borrowLimit) external returns (bool); function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) external returns (bool); function getTokenLiquidityAmountWithInterest(address payable userAddr) external view returns (uint256); function getUserAmountWithInterest(address payable userAddr) external view returns (uint256, uint256); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getUserMaxBorrowAmount(address payable userAddr) external view returns (uint256); function getUserMaxWithdrawAmount(address payable userAddr) external view returns (uint256); function getUserMaxRepayAmount(address payable userAddr) external view returns (uint256); function checkFirstAction() external returns (bool); function applyInterest(address payable userAddr) external returns (uint256, uint256); function reserveDeposit(uint256 unifiedTokenAmount) external payable returns (bool); function reserveWithdraw(uint256 unifiedTokenAmount) external returns (bool); function withdrawFlashloanFee(uint256 unifiedTokenAmount) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function getSIRandBIR() external view returns (uint256, uint256); function getERC20Addr() external view returns (address); } // File: contracts/interfaces/IMarketHandlerDataStorage.sol pragma solidity 0.6.12; /** * @title BiFi's market handler data storage interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketHandlerDataStorage { function setCircuitBreaker(bool _emergency) external returns (bool); function setNewCustomer(address payable userAddr) external returns (bool); function getUserAccessed(address payable userAddr) external view returns (bool); function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool); function getReservedAddr() external view returns (address payable); function setReservedAddr(address payable reservedAddress) external returns (bool); function getReservedAmount() external view returns (int256); function addReservedAmount(uint256 amount) external returns (int256); function subReservedAmount(uint256 amount) external returns (int256); function updateSignedReservedAmount(int256 amount) external returns (int256); function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function addDepositTotalAmount(uint256 amount) external returns (uint256); function subDepositTotalAmount(uint256 amount) external returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function addBorrowTotalAmount(uint256 amount) external returns (uint256); function subBorrowTotalAmount(uint256 amount) external returns (uint256); function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256); function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256); function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getHandlerAmount() external view returns (uint256, uint256); function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256); function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256); function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool); function getLastUpdatedBlock() external view returns (uint256); function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool); function getInactiveActionDelta() external view returns (uint256); function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool); function syncActionEXR() external returns (bool); function getActionEXR() external view returns (uint256, uint256); function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool); function getGlobalDepositEXR() external view returns (uint256); function getGlobalBorrowEXR() external view returns (uint256); function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool); function getUserEXR(address payable userAddr) external view returns (uint256, uint256); function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool); function getGlobalEXR() external view returns (uint256, uint256); function getMarketHandlerAddr() external view returns (address); function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool); function getInterestModelAddr() external view returns (address); function setInterestModelAddr(address interestModelAddr) external returns (bool); function getMinimumInterestRate() external view returns (uint256); function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool); function getLiquiditySensitivity() external view returns (uint256); function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool); function getLimit() external view returns (uint256, uint256); function getBorrowLimit() external view returns (uint256); function setBorrowLimit(uint256 _borrowLimit) external returns (bool); function getMarginCallLimit() external view returns (uint256); function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool); function getLimitOfAction() external view returns (uint256); function setLimitOfAction(uint256 limitOfAction) external returns (bool); function getLiquidityLimit() external view returns (uint256); function setLiquidityLimit(uint256 liquidityLimit) external returns (bool); } // File: contracts/interfaces/IMarketManager.sol pragma solidity 0.6.12; /** * @title BiFi's market manager interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketManager { function setBreakerTable(address _target, bool _status) external returns (bool); function getCircuitBreaker() external view returns (bool); function setCircuitBreaker(bool _emergency) external returns (bool); function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory); function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate) external returns (bool); function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256); function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256); function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256); function getTokenHandlerSupport(uint256 handlerID) external view returns (bool); function getTokenHandlersLength() external view returns (uint256); function setTokenHandlersLength(uint256 _tokenHandlerLength) external returns (bool); function getTokenHandlerID(uint256 index) external view returns (uint256); function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256); function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256); function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256); function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256); function getUserCollateralizableAmount(address payable userAddr, uint256 handlerID) external view returns (uint256); function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256); function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) external returns (uint256, uint256, uint256); function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256); function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) external returns (uint256); function setLiquidationManager(address liquidationManagerAddr) external returns (bool); function rewardClaimAll(address payable userAddr) external returns (uint256); function updateRewardParams(address payable userAddr) external returns (bool); function interestUpdateReward() external returns (bool); function getGlobalRewardInfo() external view returns (uint256, uint256, uint256); function setOracleProxy(address oracleProxyAddr) external returns (bool); function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool); function ownerRewardTransfer(uint256 _amount) external returns (bool); function getFeeTotal(uint256 handlerID) external returns (uint256); function getFeeFromArguments(uint256 handlerID, uint256 amount, uint256 bifiAmount) external returns (uint256); } // File: contracts/interfaces/IInterestModel.sol pragma solidity 0.6.12; /** * @title BiFi's interest model interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IInterestModel { function getInterestAmount(address handlerDataStorageAddr, address payable userAddr, bool isView) external view returns (bool, uint256, uint256, bool, uint256, uint256); function viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) external view returns (bool, uint256, uint256, bool, uint256, uint256); function getSIRandBIR(uint256 depositTotalAmount, uint256 borrowTotalAmount) external view returns (uint256, uint256); } // File: contracts/interfaces/IMarketSIHandlerDataStorage.sol pragma solidity 0.6.12; /** * @title BiFi's market si handler data storage interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketSIHandlerDataStorage { function setCircuitBreaker(bool _emergency) external returns (bool); function updateRewardPerBlockStorage(uint256 _rewardPerBlock) external returns (bool); function getRewardInfo(address userAddr) external view returns (uint256, uint256, uint256, uint256, uint256, uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function setMarketRewardInfo(uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardPerBlock) external returns (bool); function getUserRewardInfo(address userAddr) external view returns (uint256, uint256, uint256); function setUserRewardInfo(address userAddr, uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardAmount) external returns (bool); function getBetaRate() external view returns (uint256); function setBetaRate(uint256 _betaRate) external returns (bool); } // File: contracts/interfaces/IERC20.sol // from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external ; 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 ; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/IProxy.sol pragma solidity 0.6.12; /** * @title BiFi's proxy interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IProxy { function handlerProxy(bytes memory data) external returns (bool, bytes memory); function handlerViewProxy(bytes memory data) external view returns (bool, bytes memory); function siProxy(bytes memory data) external returns (bool, bytes memory); function siViewProxy(bytes memory data) external view returns (bool, bytes memory); } // File: contracts/interfaces/IServiceIncentive.sol pragma solidity 0.6.12; /** * @title BiFi's si interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IServiceIncentive { function setCircuitBreakWithOwner(bool emergency) external returns (bool); function setCircuitBreaker(bool emergency) external returns (bool); function updateRewardPerBlockLogic(uint256 _rewardPerBlock) external returns (bool); function updateRewardLane(address payable userAddr) external returns (bool); function getBetaRateBaseTotalAmount() external view returns (uint256); function getBetaRateBaseUserAmount(address payable userAddr) external view returns (uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function getUserRewardInfo(address payable userAddr) external view returns (uint256, uint256, uint256); function claimRewardAmountUser(address payable userAddr) external returns (uint256); } // File: contracts/interfaces/IFlashloanReceiver.sol pragma solidity 0.6.12; interface IFlashloanReceiver { function executeOperation( address reserve, uint256 amount, uint256 fee, bytes calldata params ) external returns (bool); } // File: contracts/interfaces/IinterchainManager.sol pragma solidity 0.6.12; /** * @title Bifrost's interchain manager interfaces * @author Bifrost(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IinterchainManager { function executeOutflow(address _userAddr, uint256 _btcAmount, uint256 actionType) external returns (bool); } // File: contracts/Errors.sol pragma solidity 0.6.12; contract Modifier { string internal constant ONLY_OWNER = "O"; string internal constant ONLY_MANAGER = "M"; string internal constant CIRCUIT_BREAKER = "emergency"; } contract ManagerModifier is Modifier { string internal constant ONLY_HANDLER = "H"; string internal constant ONLY_LIQUIDATION_MANAGER = "LM"; string internal constant ONLY_BREAKER = "B"; } contract HandlerDataStorageModifier is Modifier { string internal constant ONLY_BIFI_CONTRACT = "BF"; } contract SIDataStorageModifier is Modifier { string internal constant ONLY_SI_HANDLER = "SI"; } contract HandlerErrors is Modifier { string internal constant USE_VAULE = "use value"; string internal constant USE_ARG = "use arg"; string internal constant EXCEED_LIMIT = "exceed limit"; string internal constant NO_LIQUIDATION = "no liquidation"; string internal constant NO_LIQUIDATION_REWARD = "no enough reward"; string internal constant NO_EFFECTIVE_BALANCE = "not enough balance"; string internal constant TRANSFER = "err transfer"; } contract SIErrors is Modifier { } contract InterestErrors is Modifier { } contract LiquidationManagerErrors is Modifier { string internal constant NO_DELINQUENT = "not delinquent"; } contract ManagerErrors is ManagerModifier { string internal constant REWARD_TRANSFER = "RT"; string internal constant UNSUPPORTED_TOKEN = "UT"; } contract OracleProxyErrors is Modifier { string internal constant ZERO_PRICE = "price zero"; } contract RequestProxyErrors is Modifier { } contract ManagerDataStorageErrors is ManagerModifier { string internal constant NULL_ADDRESS = "err addr null"; } // File: contracts/context/BlockContext.sol pragma solidity 0.6.12; /** * @title BiFi's BlockContext contract * @notice BiFi getter Contract for Block Context Information * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract BlockContext { function _blockContext() internal view returns(uint256 context) { // block number chain context = block.number; // block timestamp chain // context = block.timestamp; } } // File: contracts/marketHandler/TokenHandler.sol // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; /** * @title BiFi's TokenHandler logic contract for ERC20 tokens * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract TokenHandler is IMarketHandler, HandlerErrors, BlockContext { event MarketIn(address userAddr); event Deposit(address depositor, uint256 depositAmount, uint256 handlerID); event DepositTo(address from, address depositor, uint256 depositAmount, uint256 handlerID); event Withdraw(address redeemer, uint256 redeemAmount, uint256 handlerID); event Borrow(address borrower, uint256 borrowAmount, uint256 handlerID); event Repay(address repayer, uint256 repayAmount, uint256 handlerID); event RepayTo(address from, address repayer, uint256 repayAmount, uint256 handlerID); event ExternalWithdraw(address redeemer, uint256 redeemAmount, uint256 handlerID); event ExternalBorrow(address borrower, uint256 borrowAmount, uint256 handlerID); event ReserveDeposit(uint256 reserveDepositAmount, uint256 handlerID); event ReserveWithdraw(uint256 reserveWithdrawAmount, uint256 handlerID); event FlashloanFeeWithdraw(uint256 flashloanFeeWithdrawAmount, uint256 handlerID); event OwnershipTransferred(address owner, address newOwner); event CircuitBreaked(bool breaked, uint256 blockNumber, uint256 handlerID); address payable owner; uint256 handlerID; string tokenName; uint256 constant unifiedPoint = 10 ** 18; uint256 unifiedTokenDecimal; uint256 underlyingTokenDecimal; IMarketManager marketManager; IInterestModel interestModelInstance; IMarketHandlerDataStorage handlerDataStorage; IMarketSIHandlerDataStorage SIHandlerDataStorage; IERC20 erc20Instance; address handler; address SI; IinterchainManager interchainManager; struct ProxyInfo { bool result; bytes returnData; bytes data; bytes proxyData; } modifier onlyMarketManager { address msgSender = msg.sender; require((msgSender == address(marketManager)) || (msgSender == owner), ONLY_MANAGER); _; } modifier onlyOwner { require(msg.sender == address(owner), ONLY_OWNER); _; } /** * @dev Set circuitBreak to freeze all of handlers by owner * @param _emergency Boolean state of the circuit break. * @return true (TODO: validate results) */ function setCircuitBreakWithOwner(bool _emergency) onlyOwner external override returns (bool) { handlerDataStorage.setCircuitBreaker(_emergency); emit CircuitBreaked(_emergency, block.number, handlerID); return true; } /** * @dev Set circuitBreak which freeze all of handlers by marketManager * @param _emergency Boolean state of the circuit break. * @return true (TODO: validate results) */ function setCircuitBreaker(bool _emergency) onlyMarketManager external override returns (bool) { handlerDataStorage.setCircuitBreaker(_emergency); emit CircuitBreaked(_emergency, block.number, handlerID); return true; } /** * @dev Change the owner of the handler * @param newOwner the address of the owner to be replaced * @return true (TODO: validate results) */ function ownershipTransfer(address payable newOwner) onlyOwner external override returns (bool) { owner = newOwner; emit OwnershipTransferred(owner, newOwner); return true; } /** * @dev Get the token name * @return the token name */ function getTokenName() external view override returns (string memory) { return tokenName; } /** * @dev Deposit assets to the reserve of the handler. * @param unifiedTokenAmount The amount of token to deposit * @return true (TODO: validate results) */ function reserveDeposit(uint256 unifiedTokenAmount) external payable override returns (bool) { require(msg.value == 0, USE_ARG); handlerDataStorage.addReservedAmount(unifiedTokenAmount); handlerDataStorage.addDepositTotalAmount(unifiedTokenAmount); _transferFrom(msg.sender, unifiedTokenAmount); emit ReserveDeposit(unifiedTokenAmount, handlerID); return true; } /** * @dev Withdraw assets from the reserve of the handler. * @param unifiedTokenAmount The amount of token to withdraw * @return true (TODO: validate results) */ function reserveWithdraw(uint256 unifiedTokenAmount) onlyOwner external override returns (bool) { address payable reserveAddr = handlerDataStorage.getReservedAddr(); handlerDataStorage.subReservedAmount(unifiedTokenAmount); handlerDataStorage.subDepositTotalAmount(unifiedTokenAmount); _transfer(reserveAddr, unifiedTokenAmount); emit ReserveWithdraw(unifiedTokenAmount, handlerID); return true; } function withdrawFlashloanFee(uint256 unifiedTokenAmount) onlyMarketManager external override returns (bool) { address payable reserveAddr = handlerDataStorage.getReservedAddr(); handlerDataStorage.subReservedAmount(unifiedTokenAmount); handlerDataStorage.subDepositTotalAmount(unifiedTokenAmount); _transfer(reserveAddr, unifiedTokenAmount); emit FlashloanFeeWithdraw(unifiedTokenAmount, handlerID); return true; } /** * @dev Deposit action * @param unifiedTokenAmount The deposit amount * @param flag Flag for the full calcuation mode * @return true (TODO: validate results) */ function deposit(uint256 unifiedTokenAmount, bool flag) external payable override returns (bool) { require(msg.value == 0, USE_ARG); address payable userAddr = msg.sender; uint256 _handlerID = handlerID; if(flag) { // flag is true, update interest, reward all handlers marketManager.applyInterestHandlers(userAddr, _handlerID, flag); } else { marketManager.rewardUpdateOfInAction(userAddr, _handlerID); _applyInterest(userAddr); } handlerDataStorage.addDepositAmount(userAddr, unifiedTokenAmount); _transferFrom(userAddr, unifiedTokenAmount); emit Deposit(userAddr, unifiedTokenAmount, _handlerID); return true; } function depositTo(address payable toUser, uint256 unifiedTokenAmount, bool flag) external returns (bool) { uint256 _handlerID = handlerID; address payable _sender = msg.sender; if(flag) { // flag is true, update interest, reward all handlers marketManager.applyInterestHandlers(toUser, _handlerID, flag); } else { marketManager.rewardUpdateOfInAction(toUser, _handlerID); _applyInterest(toUser); } handlerDataStorage.addDepositAmount(toUser, unifiedTokenAmount); _transferFrom(_sender, unifiedTokenAmount); emit DepositTo(_sender, toUser, unifiedTokenAmount, _handlerID); return true; } /** * @dev Withdraw action * @param unifiedTokenAmount The withdraw amount * @param flag Flag for the full calcuation mode * @return true (TODO: validate results) */ function withdraw(uint256 unifiedTokenAmount, bool flag) external override returns (bool) { address payable userAddr = msg.sender; uint256 _handlerID = handlerID; uint256 userLiquidityAmount; uint256 userCollateralizableAmount; uint256 price; (userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag); uint256 adjustedAmount = _getUserActionMaxWithdrawAmount(userAddr, unifiedTokenAmount, userCollateralizableAmount); require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT); handlerDataStorage.subDepositAmount(userAddr, adjustedAmount); _transfer(userAddr, adjustedAmount); emit Withdraw(userAddr, adjustedAmount, _handlerID); return true; } /** * @dev Borrow action * @param unifiedTokenAmount The borrow amount * @param flag Flag for the full calcuation mode * @return true (TODO: validate results) */ function borrow(uint256 unifiedTokenAmount, bool flag) external override returns (bool) { address payable userAddr = msg.sender; uint256 _handlerID = handlerID; uint256 userLiquidityAmount; uint256 userCollateralizableAmount; uint256 price; (userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag); uint256 adjustedAmount = _getUserActionMaxBorrowAmount(unifiedTokenAmount, userLiquidityAmount); require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT); handlerDataStorage.addBorrowAmount(userAddr, adjustedAmount); _transfer(userAddr, adjustedAmount); emit Borrow(userAddr, adjustedAmount, _handlerID); return true; } /** * @dev Repay action * @param unifiedTokenAmount The repay amount * @param flag Flag for the full calcuation mode * @return true (TODO: validate results) */ function repay(uint256 unifiedTokenAmount, bool flag) external payable override returns (bool) { require(msg.value == 0, USE_ARG); address payable userAddr = msg.sender; uint256 _handlerID = handlerID; if(flag) { // flag is true, update interest, reward all handlers marketManager.applyInterestHandlers(userAddr, _handlerID, flag); } else { marketManager.rewardUpdateOfInAction(userAddr, _handlerID); _applyInterest(userAddr); } uint256 userBorrowAmount = handlerDataStorage.getUserIntraBorrowAmount(userAddr); if (userBorrowAmount < unifiedTokenAmount) { unifiedTokenAmount = userBorrowAmount; } handlerDataStorage.subBorrowAmount(userAddr, unifiedTokenAmount); _transferFrom(userAddr, unifiedTokenAmount); emit Repay(userAddr, unifiedTokenAmount, _handlerID); return true; } function repayTo(address payable toUser, uint256 unifiedTokenAmount, bool flag) external returns (bool) { uint256 _handlerID = handlerID; address _sender = msg.sender; if(flag) { // flag is true, update interest, reward all handlers marketManager.applyInterestHandlers(toUser, _handlerID, flag); } else { marketManager.rewardUpdateOfInAction(toUser, _handlerID); _applyInterest(toUser); } uint256 userBorrowAmount = handlerDataStorage.getUserIntraBorrowAmount(toUser); if (userBorrowAmount < unifiedTokenAmount) { handlerDataStorage.subBorrowAmount(toUser, userBorrowAmount); handlerDataStorage.addDepositAmount(toUser, sub(unifiedTokenAmount, userBorrowAmount) ); emit Deposit(toUser, sub(unifiedTokenAmount, userBorrowAmount), _handlerID); } else { handlerDataStorage.subBorrowAmount(toUser, unifiedTokenAmount); } _transferFrom(msg.sender, unifiedTokenAmount); emit RepayTo(_sender, toUser, unifiedTokenAmount, _handlerID); return true; } function reqExternalWithdraw(uint256 unifiedTokenAmount, bool flag) external returns (bool) { address payable userAddr = msg.sender; uint256 _handlerID = handlerID; uint256 userLiquidityAmount; uint256 userCollateralizableAmount; uint256 price; (userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag); uint256 adjustedAmount = _getUserActionMaxWithdrawAmount(userAddr, unifiedTokenAmount, userCollateralizableAmount); require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT); handlerDataStorage.subDepositAmount(userAddr, adjustedAmount); uint256 underlyingAmount = _approve(address(interchainManager), adjustedAmount); interchainManager.executeOutflow(userAddr, underlyingAmount, 2); emit ExternalWithdraw(userAddr, adjustedAmount, _handlerID); return true; } function reqExternalborrow(uint256 unifiedTokenAmount, bool flag) external returns (bool) { address payable userAddr = msg.sender; uint256 _handlerID = handlerID; uint256 userLiquidityAmount; uint256 userCollateralizableAmount; uint256 price; (userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag); uint256 adjustedAmount = _getUserActionMaxBorrowAmount(unifiedTokenAmount, userLiquidityAmount); require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT); handlerDataStorage.addBorrowAmount(userAddr, adjustedAmount); uint256 underlyingAmount = _approve(address(interchainManager), adjustedAmount); interchainManager.executeOutflow(userAddr, underlyingAmount, 3); emit ExternalBorrow(userAddr, adjustedAmount, _handlerID); return true; } function executeFlashloan( address receiverAddress, uint256 amount ) external onlyMarketManager override returns (bool) { _transfer(payable(receiverAddress), amount); return true; } function depositFlashloanFee( uint256 amount ) external onlyMarketManager override returns (bool) { handlerDataStorage.addReservedAmount(amount); handlerDataStorage.addDepositTotalAmount(amount); emit ReserveDeposit(amount, handlerID); return true; } /** * @dev liquidate delinquentBorrower's partial(or can total) asset * @param delinquentBorrower The user addresss of liquidation target * @param liquidateAmount The amount of liquidator request * @param liquidator The address of a user executing liquidate * @param rewardHandlerID The handler id of delinquentBorrower's collateral for receive * @return (liquidateAmount, delinquentDepositAsset, delinquentBorrowAsset), result of liquidate */ function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) onlyMarketManager external override returns (uint256, uint256, uint256) { /* over paied amount compaction */ uint256 tmp; uint256 delinquentMarginCallDeposit; uint256 delinquentDepositAsset; uint256 delinquentBorrowAsset; uint256 liquidatorLiquidityAmount; /* apply interest for sync "latest" asset for delinquentBorrower and liquidator */ (, , delinquentMarginCallDeposit, delinquentDepositAsset, delinquentBorrowAsset, ) = marketManager.applyInterestHandlers(delinquentBorrower, handlerID, false); (, liquidatorLiquidityAmount, , , , ) = marketManager.applyInterestHandlers(liquidator, handlerID, false); /* check delinquentBorrower liquidatable */ require(delinquentMarginCallDeposit <= delinquentBorrowAsset, NO_LIQUIDATION); tmp = handlerDataStorage.getUserIntraDepositAmount(liquidator); if (tmp <= liquidateAmount) { liquidateAmount = tmp; } tmp = handlerDataStorage.getUserIntraBorrowAmount(delinquentBorrower); if (tmp <= liquidateAmount) { liquidateAmount = tmp; } /* get maximum "receive handler" amount by liquidate amount */ liquidateAmount = marketManager.getMaxLiquidationReward(delinquentBorrower, handlerID, liquidateAmount, rewardHandlerID, unifiedDiv(delinquentBorrowAsset, delinquentDepositAsset)); /* check liquidator has enough amount for liquidation */ require(liquidatorLiquidityAmount > liquidateAmount, NO_EFFECTIVE_BALANCE); /* update storage for liquidate*/ handlerDataStorage.subDepositAmount(liquidator, liquidateAmount); handlerDataStorage.subBorrowAmount(delinquentBorrower, liquidateAmount); return (liquidateAmount, delinquentDepositAsset, delinquentBorrowAsset); } /** * @dev liquidator receive delinquentBorrower's collateral after liquidate delinquentBorrower's asset * @param delinquentBorrower The user addresss of liquidation target * @param liquidationAmountWithReward The amount of liquidator receiving delinquentBorrower's collateral * @param liquidator The address of a user executing liquidate * @return The amount of token transfered(in storage) */ function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) onlyMarketManager external override returns (uint256) { marketManager.rewardUpdateOfInAction(delinquentBorrower, handlerID); _applyInterest(delinquentBorrower); /* check delinquentBorrower's collateral enough */ uint256 collateralAmount = handlerDataStorage.getUserIntraDepositAmount(delinquentBorrower); require(collateralAmount >= liquidationAmountWithReward, NO_LIQUIDATION_REWARD); /* collateral transfer */ handlerDataStorage.subDepositAmount(delinquentBorrower, liquidationAmountWithReward); _transfer(liquidator, liquidationAmountWithReward); return liquidationAmountWithReward; } /** * @dev Get borrowLimit and marginCallLimit * @return borrowLimit and marginCallLimit */ function getTokenHandlerLimit() external view override returns (uint256, uint256) { return handlerDataStorage.getLimit(); } /** * @dev Set the borrow limit of the handler through a specific handlerID * @param borrowLimit The borrow limit * @return true (TODO: validate results) */ function setTokenHandlerBorrowLimit(uint256 borrowLimit) onlyOwner external override returns (bool) { handlerDataStorage.setBorrowLimit(borrowLimit); return true; } /** * @dev Set the liquidation limit of the handler through a specific handlerID * @param marginCallLimit The liquidation limit * @return true (TODO: validate results) */ function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) onlyOwner external override returns (bool) { handlerDataStorage.setMarginCallLimit(marginCallLimit); return true; } /** * @dev Get the liquidation limit of handler through a specific handlerID * @return The liquidation limit */ function getTokenHandlerMarginCallLimit() external view override returns (uint256) { return handlerDataStorage.getMarginCallLimit(); } /** * @dev Get the borrow limit of the handler through a specific handlerID * @return The borrow limit */ function getTokenHandlerBorrowLimit() external view override returns (uint256) { return handlerDataStorage.getBorrowLimit(); } /** * @dev Get the maximum amount that user can borrow * @param userAddr The address of user * @return the maximum amount that user can borrow */ function getUserMaxBorrowAmount(address payable userAddr) external view override returns (uint256) { return _getUserMaxBorrowAmount(userAddr); } /** * @dev Get (total deposit - total borrow) of the handler including interest * @param userAddr The user address(for wrapping function, unused) * @return (total deposit - total borrow) of the handler including interest */ function getTokenLiquidityAmountWithInterest(address payable userAddr) external view override returns (uint256) { return _getTokenLiquidityAmountWithInterest(userAddr); } /** * @dev Get the maximum amount that user can borrow * @param userAddr The address of user * @return the maximum amount that user can borrow */ function _getUserMaxBorrowAmount(address payable userAddr) internal view returns (uint256) { /* Prevent Action: over "Token Liquidity" amount*/ uint256 handlerLiquidityAmount = _getTokenLiquidityLimitAmountWithInterest(userAddr); /* Prevent Action: over "CREDIT" amount */ uint256 userLiquidityAmount = marketManager.getUserExtraLiquidityAmount(userAddr, handlerID); uint256 minAmount = userLiquidityAmount; if (handlerLiquidityAmount < minAmount) { minAmount = handlerLiquidityAmount; } return minAmount; } /** * @dev Get the maximum amount that user can borrow * @param requestedAmount The amount of token to borrow * @param userLiquidityAmount The amount of liquidity that users can borrow * @return the maximum amount that user can borrow */ function _getUserActionMaxBorrowAmount(uint256 requestedAmount, uint256 userLiquidityAmount) internal view returns (uint256) { /* Prevent Action: over "Token Liquidity" amount*/ uint256 handlerLiquidityAmount = _getTokenLiquidityLimitAmount(); /* select minimum of handlerLiqudity and user liquidity */ uint256 minAmount = requestedAmount; if (minAmount > handlerLiquidityAmount) { minAmount = handlerLiquidityAmount; } if (minAmount > userLiquidityAmount) { minAmount = userLiquidityAmount; } return minAmount; } /** * @dev Get the maximum amount that users can withdraw * @param userAddr The address of user * @return the maximum amount that users can withdraw */ function getUserMaxWithdrawAmount(address payable userAddr) external view override returns (uint256) { return _getUserMaxWithdrawAmount(userAddr); } /** * @dev Get the rate of SIR and BIR * @return The rate of SIR and BIR */ function getSIRandBIR() external view override returns (uint256, uint256) { uint256 totalDepositAmount = handlerDataStorage.getDepositTotalAmount(); uint256 totalBorrowAmount = handlerDataStorage.getBorrowTotalAmount(); return interestModelInstance.getSIRandBIR(totalDepositAmount, totalBorrowAmount); } /** * @dev Get the maximum amount that users can withdraw * @param userAddr The address of user * @return the maximum amount that users can withdraw */ function _getUserMaxWithdrawAmount(address payable userAddr) internal view returns (uint256) { uint256 depositAmountWithInterest; uint256 borrowAmountWithInterest; (depositAmountWithInterest, borrowAmountWithInterest) = _getUserAmountWithInterest(userAddr); uint256 handlerLiquidityAmount = _getTokenLiquidityAmountWithInterest(userAddr); uint256 userLiquidityAmount = marketManager.getUserCollateralizableAmount(userAddr, handlerID); /* Prevent Action: over "DEPOSIT" amount */ uint256 minAmount = depositAmountWithInterest; /* Prevent Action: over "CREDIT" amount */ if (minAmount > userLiquidityAmount) { minAmount = userLiquidityAmount; } if (minAmount > handlerLiquidityAmount) { minAmount = handlerLiquidityAmount; } return minAmount; } /** * @dev Get the maximum amount that users can withdraw * @param userAddr The address of user * @param requestedAmount The amount of token to withdraw * @param collateralableAmount The amount of liquidity that users can borrow * @return the maximum amount that users can withdraw */ function _getUserActionMaxWithdrawAmount(address payable userAddr, uint256 requestedAmount, uint256 collateralableAmount) internal view returns (uint256) { uint256 depositAmount = handlerDataStorage.getUserIntraDepositAmount(userAddr); uint256 handlerLiquidityAmount = _getTokenLiquidityAmount(); /* select minimum among deposited, requested and collateralable*/ uint256 minAmount = depositAmount; if (minAmount > requestedAmount) { minAmount = requestedAmount; } if (minAmount > collateralableAmount) { minAmount = collateralableAmount; } if (minAmount > handlerLiquidityAmount) { minAmount = handlerLiquidityAmount; } return minAmount; } /** * @dev Get the maximum amount that users can repay * @param userAddr The address of user * @return the maximum amount that users can repay */ function getUserMaxRepayAmount(address payable userAddr) external view override returns (uint256) { uint256 depositAmountWithInterest; uint256 borrowAmountWithInterest; (depositAmountWithInterest, borrowAmountWithInterest) = _getUserAmountWithInterest(userAddr); return borrowAmountWithInterest; } /** * @dev Update (apply) interest entry point (external) * @param userAddr The user address * @return "latest" (userDepositAmount, userBorrowAmount) */ function applyInterest(address payable userAddr) external override returns (uint256, uint256) { return _applyInterest(userAddr); } /** * @dev Update (apply) interest entry point (external) * @param userAddr The user address * @return "latest" (userDepositAmount, userBorrowAmount) */ function _applyInterest(address payable userAddr) internal returns (uint256, uint256) { _checkNewCustomer(userAddr); _checkFirstAction(); return _updateInterestAmount(userAddr); } /** * @dev Check whether a given userAddr is a new user or not * @param userAddr The user address * @return true if the user is a new user; false otherwise. */ function _checkNewCustomer(address payable userAddr) internal returns (bool) { IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage; if (_handlerDataStorage.getUserAccessed(userAddr)) { return false; } /* hotfix */ _handlerDataStorage.setUserAccessed(userAddr, true); (uint256 gDEXR, uint256 gBEXR) = _handlerDataStorage.getGlobalEXR(); _handlerDataStorage.setUserEXR(userAddr, gDEXR, gBEXR); return true; } /** * @dev Get the address of the token that the handler is dealing with * (CoinHandler don't deal with tokens in coin handlers) * @return The address of the token */ function getERC20Addr() external override view returns (address) { return address(erc20Instance); } /** * @dev Get the amount of deposit and borrow of the user * @param userAddr The address of user * (depositAmount, borrowAmount) */ function getUserAmount(address payable userAddr) external view override returns (uint256, uint256) { uint256 depositAmount = handlerDataStorage.getUserIntraDepositAmount(userAddr); uint256 borrowAmount = handlerDataStorage.getUserIntraBorrowAmount(userAddr); return (depositAmount, borrowAmount); } /** * @dev Get the amount of user's deposit * @param userAddr The address of user * @return the amount of user's deposit */ function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256) { return handlerDataStorage.getUserIntraDepositAmount(userAddr); } /** * @dev Get the amount of user's borrow * @param userAddr The address of user * @return the amount of user's borrow */ function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256) { return handlerDataStorage.getUserIntraBorrowAmount(userAddr); } /** * @dev Get the amount of handler's total deposit * @return the amount of handler's total deposit */ function getDepositTotalAmount() external view override returns (uint256) { return handlerDataStorage.getDepositTotalAmount(); } /** * @dev Get the amount of handler's total borrow * @return the amount of handler's total borrow */ function getBorrowTotalAmount() external view override returns (uint256) { return handlerDataStorage.getBorrowTotalAmount(); } /** * @dev Get the amount of deposit and borrow of user including interest * @param userAddr The user address * @return (userDepositAmount, userBorrowAmount) */ function getUserAmountWithInterest(address payable userAddr) external view override returns (uint256, uint256) { return _getUserAmountWithInterest(userAddr); } /** * @dev Get the address of owner * @return the address of owner */ function getOwner() public view returns (address) { return owner; } /** * @dev Check first action of user in the This Block (external) * @return true for first action */ function checkFirstAction() onlyMarketManager external override returns (bool) { return _checkFirstAction(); } /** * @dev Convert amount of handler's unified decimals to amount of token's underlying decimals * @param unifiedTokenAmount The amount of unified decimals * @return (underlyingTokenAmount) */ function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external override view returns (uint256) { return _convertUnifiedToUnderlying(unifiedTokenAmount); } /** * @dev Check first action of user in the This Block (external) * @return true for first action */ function _checkFirstAction() internal returns (bool) { IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage; uint256 lastUpdatedBlock = _handlerDataStorage.getLastUpdatedBlock(); uint256 currentBlockNumber = _blockContext(); uint256 blockDelta = sub(currentBlockNumber, lastUpdatedBlock); if (blockDelta > 0) { _handlerDataStorage.setBlocks(currentBlockNumber, blockDelta); _handlerDataStorage.syncActionEXR(); return true; } return false; } /** * @dev calculate (apply) interest (internal) and call storage update function * @param userAddr The user address * @return "latest" (userDepositAmount, userBorrowAmount) */ function _updateInterestAmount(address payable userAddr) internal returns (uint256, uint256) { bool depositNegativeFlag; uint256 deltaDepositAmount; uint256 globalDepositEXR; bool borrowNegativeFlag; uint256 deltaBorrowAmount; uint256 globalBorrowEXR; /* calculate interest amount and params by call Interest Model */ (depositNegativeFlag, deltaDepositAmount, globalDepositEXR, borrowNegativeFlag, deltaBorrowAmount, globalBorrowEXR) = interestModelInstance.getInterestAmount(address(handlerDataStorage), userAddr, false); /* update new global EXR to user EXR*/ handlerDataStorage.setEXR(userAddr, globalDepositEXR, globalBorrowEXR); /* call storage update function for update "latest" interest information */ return _setAmountReflectInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount); } /** * @dev Apply the user's interest * @param userAddr The user address * @param depositNegativeFlag the sign of deltaDepositAmount (true for negative) * @param deltaDepositAmount The delta amount of deposit * @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative) * @param deltaBorrowAmount The delta amount of borrow * @return "latest" (userDepositAmount, userBorrowAmount) */ function _setAmountReflectInterest(address payable userAddr, bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal returns (uint256, uint256) { uint256 depositTotalAmount; uint256 userDepositAmount; uint256 borrowTotalAmount; uint256 userBorrowAmount; /* call _getAmountWithInterest for adding user storage amount and interest delta amount (deposit and borrow)*/ (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _getAmountWithInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount); /* update user amount in storage*/ handlerDataStorage.setAmount(userAddr, depositTotalAmount, borrowTotalAmount, userDepositAmount, userBorrowAmount); /* update "spread between deposits and borrows" */ _updateReservedAmount(depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount); return (userDepositAmount, userBorrowAmount); } /** * @dev Get the "latest" user amount of deposit and borrow including interest (internal, view) * @param userAddr The user address * @return "latest" (userDepositAmount, userBorrowAmount) */ function _getUserAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256) { uint256 depositTotalAmount; uint256 userDepositAmount; uint256 borrowTotalAmount; uint256 userBorrowAmount; (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _calcAmountWithInterest(userAddr); return (userDepositAmount, userBorrowAmount); } /** * @dev Get the "latest" handler amount of deposit and borrow including interest (internal, view) * @param userAddr The user address * @return "latest" (depositTotalAmount, borrowTotalAmount) */ function _getTotalAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256) { uint256 depositTotalAmount; uint256 userDepositAmount; uint256 borrowTotalAmount; uint256 userBorrowAmount; (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _calcAmountWithInterest(userAddr); return (depositTotalAmount, borrowTotalAmount); } /** * @dev The deposit and borrow amount with interest for the user * @param userAddr The user address * @return "latest" (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) */ function _calcAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256, uint256, uint256) { bool depositNegativeFlag; uint256 deltaDepositAmount; uint256 globalDepositEXR; bool borrowNegativeFlag; uint256 deltaBorrowAmount; uint256 globalBorrowEXR; (depositNegativeFlag, deltaDepositAmount, globalDepositEXR, borrowNegativeFlag, deltaBorrowAmount, globalBorrowEXR) = interestModelInstance.getInterestAmount(address(handlerDataStorage), userAddr, true); return _getAmountWithInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount); } /** * @dev Calculate "latest" amount with interest for the block delta * @param userAddr The user address * @param depositNegativeFlag the sign of deltaDepositAmount (true for negative) * @param deltaDepositAmount The delta amount of deposit * @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative) * @param deltaBorrowAmount The delta amount of borrow * @return "latest" (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) */ function _getAmountWithInterest(address payable userAddr, bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal view returns (uint256, uint256, uint256, uint256) { uint256 depositTotalAmount; uint256 userDepositAmount; uint256 borrowTotalAmount; uint256 userBorrowAmount; (depositTotalAmount, borrowTotalAmount, userDepositAmount, userBorrowAmount) = handlerDataStorage.getAmount(userAddr); if (depositNegativeFlag) { depositTotalAmount = sub(depositTotalAmount, deltaDepositAmount); userDepositAmount = sub(userDepositAmount, deltaDepositAmount); } else { depositTotalAmount = add(depositTotalAmount, deltaDepositAmount); userDepositAmount = add(userDepositAmount, deltaDepositAmount); } if (borrowNegativeFlag) { borrowTotalAmount = sub(borrowTotalAmount, deltaBorrowAmount); userBorrowAmount = sub(userBorrowAmount, deltaBorrowAmount); } else { borrowTotalAmount = add(borrowTotalAmount, deltaBorrowAmount); userBorrowAmount = add(userBorrowAmount, deltaBorrowAmount); } return (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount); } /** * @dev Update the amount of the reserve * @param depositNegativeFlag the sign of deltaDepositAmount (true for negative) * @param deltaDepositAmount The delta amount of deposit * @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative) * @param deltaBorrowAmount The delta amount of borrow * @return true (TODO: validate results) */ function _updateReservedAmount(bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal returns (bool) { int256 signedDeltaDepositAmount = int(deltaDepositAmount); int256 signedDeltaBorrowAmount = int(deltaBorrowAmount); if (depositNegativeFlag) { signedDeltaDepositAmount = signedDeltaDepositAmount * (-1); } if (borrowNegativeFlag) { signedDeltaBorrowAmount = signedDeltaBorrowAmount * (-1); } /* signedDeltaReservedAmount is singed amount */ int256 signedDeltaReservedAmount = signedSub(signedDeltaBorrowAmount, signedDeltaDepositAmount); handlerDataStorage.updateSignedReservedAmount(signedDeltaReservedAmount); return true; } /** * @dev Sends the handler's assets to the given user * @param userAddr The address of user * @param unifiedTokenAmount The amount of token to send in unified token amount * @return true (TODO: validate results) */ function _transfer(address payable userAddr, uint256 unifiedTokenAmount) internal returns (bool) { uint256 beforeBalance = erc20Instance.balanceOf(userAddr); uint256 underlyingAmount = _convertUnifiedToUnderlying(unifiedTokenAmount); erc20Instance.transfer(userAddr, underlyingAmount); uint256 afterBalance = erc20Instance.balanceOf(userAddr); require(underlyingAmount == sub(afterBalance, beforeBalance), TRANSFER); return true; } // TODO: need review function _approve(address userAddr, uint256 unifiedTokenAmount) internal returns (uint256) { uint256 beforeBalance = erc20Instance.allowance(address(this), userAddr); uint256 underlyingAmount = _convertUnifiedToUnderlying(unifiedTokenAmount); erc20Instance.approve(userAddr, underlyingAmount); uint256 afterBalance = erc20Instance.allowance(address(this), userAddr); require(underlyingAmount == sub(afterBalance, beforeBalance), TRANSFER); return underlyingAmount; } /** * @dev Sends the assets from the user to the contract * @param userAddr The address of user * @param unifiedTokenAmount The amount of token to send in unified token amount * @return true (TODO: validate results) */ function _transferFrom(address payable userAddr, uint256 unifiedTokenAmount) internal returns (bool) { uint256 beforeBalance = erc20Instance.balanceOf(userAddr); uint256 underlyingAmount = _convertUnifiedToUnderlying(unifiedTokenAmount); erc20Instance.transferFrom(userAddr, address(this), underlyingAmount); uint256 afterBalance = erc20Instance.balanceOf(userAddr); require(underlyingAmount == sub(beforeBalance, afterBalance), TRANSFER); return true; } /** * @dev Convert amount of handler's unified decimals to amount of token's underlying decimals * @param unifiedTokenAmount The amount of unified decimals * @return (underlyingTokenAmount) */ function _convertUnifiedToUnderlying(uint256 unifiedTokenAmount) internal view returns (uint256) { return div(mul(unifiedTokenAmount, underlyingTokenDecimal), unifiedTokenDecimal); } /** * @dev Convert amount of token's underlying decimals to amount of handler's unified decimals * @param underlyingTokenAmount The amount of underlying decimals * @return (unifiedTokenAmount) */ function _convertUnderlyingToUnified(uint256 underlyingTokenAmount) internal view returns (uint256) { return div(mul(underlyingTokenAmount, unifiedTokenDecimal), underlyingTokenDecimal); } /** * @dev Get (total deposit - total borrow) of the handler * @return (total deposit - total borrow) of the handler */ function _getTokenLiquidityAmount() internal view returns (uint256) { IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage; uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount(); if (depositTotalAmount == 0 || depositTotalAmount < borrowTotalAmount) { return 0; } return sub(depositTotalAmount, borrowTotalAmount); } /** * @dev Get (total deposit * liquidity limit - total borrow) of the handler * @return (total deposit * liquidity limit - total borrow) of the handler */ function _getTokenLiquidityLimitAmount() internal view returns (uint256) { IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage; uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount(); uint256 liquidityDeposit = unifiedMul(depositTotalAmount, _handlerDataStorage.getLiquidityLimit()); if (depositTotalAmount == 0 || liquidityDeposit < borrowTotalAmount) { return 0; } return sub(liquidityDeposit, borrowTotalAmount); } /** * @dev Get (total deposit - total borrow) of the handler including interest * @param userAddr The user address(for wrapping function, unused) * @return (total deposit - total borrow) of the handler including interest */ function _getTokenLiquidityAmountWithInterest(address payable userAddr) internal view returns (uint256) { uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = _getTotalAmountWithInterest(userAddr); if (depositTotalAmount == 0 || depositTotalAmount < borrowTotalAmount) { return 0; } return sub(depositTotalAmount, borrowTotalAmount); } /** * @dev Get (total deposit * liquidity limit - total borrow) of the handler including interest * @param userAddr The user address(for wrapping function, unused) * @return (total deposit * liquidity limit - total borrow) of the handler including interest */ function _getTokenLiquidityLimitAmountWithInterest(address payable userAddr) internal view returns (uint256) { uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = _getTotalAmountWithInterest(userAddr); uint256 liquidityDeposit = unifiedMul(depositTotalAmount, handlerDataStorage.getLiquidityLimit()); if (depositTotalAmount == 0 || liquidityDeposit < borrowTotalAmount) { return 0; } return sub(liquidityDeposit, borrowTotalAmount); } /** * @dev Set the unifiedPoint of token's decimal * @param _unifiedTokenDecimal the unifiedPoint of token's decimal * @return true (TODO: validate results) */ function setUnifiedTokenDecimal(uint256 _unifiedTokenDecimal) onlyOwner external returns (bool) { unifiedTokenDecimal = _unifiedTokenDecimal; return true; } /** * @dev Get the decimal of token * @return (uint256, uint256) the decimal of token and the unifiedPoint of token's decimal */ function getTokenDecimals() external view returns (uint256, uint256) { return (underlyingTokenDecimal, unifiedTokenDecimal); } /** * @dev Get the unifiedPoint of token's decimal (for fixed decimal number) * @return the unifiedPoint of token's decimal */ /* default: UnifiedTokenDecimal Function */ function getUnifiedTokenDecimal() external view returns (uint256) { return unifiedTokenDecimal; } /** * @dev Get the decimal of the underlying token * @return the decimal of the underlying token */ /* default: UnderlyingTokenDecimal Function */ function getUnderlyingTokenDecimal() external view returns (uint256) { return underlyingTokenDecimal; } /** * @dev Set the decimal of token * @param _underlyingTokenDecimal the decimal of token * @return true (TODO: validate results) */ function setUnderlyingTokenDecimal(uint256 _underlyingTokenDecimal) onlyOwner external returns (bool) { underlyingTokenDecimal = _underlyingTokenDecimal; return true; } /** * @dev Set the address of the marketManager contract * @param marketManagerAddr The address of the marketManager contract * @return true (TODO: validate results) */ function setMarketManager(address marketManagerAddr) onlyOwner public returns (bool) { marketManager = IMarketManager(marketManagerAddr); return true; } /** * @dev Set the address of the InterestModel contract * @param interestModelAddr The address of the InterestModel contract * @return true (TODO: validate results) */ function setInterestModel(address interestModelAddr) onlyOwner public returns (bool) { interestModelInstance = IInterestModel(interestModelAddr); return true; } /** * @dev Set the address of the marketDataStorage contract * @param marketDataStorageAddr The address of the marketDataStorage contract * @return true (TODO: validate results) */ function setHandlerDataStorage(address marketDataStorageAddr) onlyOwner public returns (bool) { handlerDataStorage = IMarketHandlerDataStorage(marketDataStorageAddr); return true; } /** * @dev Set the address and name of the underlying ERC-20 token * @param erc20Addr The address of ERC-20 token * @param name The name of ERC-20 token * @return true (TODO: validate results) */ function setErc20(address erc20Addr, string memory name) onlyOwner public returns (bool) { erc20Instance = IERC20(erc20Addr); tokenName = name; return true; } /** * @dev Set the address of the siHandlerDataStorage contract * @param SIHandlerDataStorageAddr The address of the siHandlerDataStorage contract * @return true (TODO: validate results) */ function setSiHandlerDataStorage(address SIHandlerDataStorageAddr) onlyOwner public returns (bool) { SIHandlerDataStorage = IMarketSIHandlerDataStorage(SIHandlerDataStorageAddr); return true; } /** * @dev Get the address of the siHandlerDataStorage contract * @return The address of the siHandlerDataStorage contract */ function getSiHandlerDataStorage() public view returns (address) { return address(SIHandlerDataStorage); } /** * @dev Get the address of the marketManager contract * @return The address of the marketManager contract */ function getMarketManagerAddr() public view returns (address) { return address(marketManager); } /** * @dev Get the address of the InterestModel contract * @return The address of the InterestModel contract */ function getInterestModelAddr() public view returns (address) { return address(interestModelInstance); } /** * @dev Get the address of handler's dataStroage * @return the address of handler's dataStroage */ function getHandlerDataStorageAddr() public view returns (address) { return address(handlerDataStorage); } /** * @dev Get the address of the underlying ERC-20 token * @return The address of the underlying ERC-20 token */ function getErc20Addr() public view returns (address) { return address(erc20Instance); } /** * @dev Get the outgoing limit of tokens * @return The outgoing limit of tokens */ function getLimitOfAction() external view returns (uint256) { return handlerDataStorage.getLimitOfAction(); } function get_interchainManager() external view returns (address) { return address(interchainManager); } function set_interchainManager(IinterchainManager _interchainManager) onlyOwner external returns (bool) { interchainManager = _interchainManager; return true; } /* ******************* Safe Math ******************* */ // from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol // Subject to the MIT license. function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "add overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return _sub(a, b, "sub overflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return _mul(a, b); } function div(uint256 a, uint256 b) internal pure returns (uint256) { return _div(a, b, "div by zero"); } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return _mod(a, b, "mod by zero"); } function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); 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, "mul overflow"); return c; } function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function _mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, unifiedPoint), b, "unified div by zero"); } function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, b), unifiedPoint, "unified mul by zero"); } function signedAdd(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; } function signedSub(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; } }
Get the decimal of the underlying token return the decimal of the underlying token/ default: UnderlyingTokenDecimal Function /
function getUnderlyingTokenDecimal() external view returns (uint256) { return underlyingTokenDecimal; }
1,420,321
./partial_match/1/0xb3877037A0B366f33Eb8BdDb4e0b477417359EcE/sources/contracts/ERC721ATest.sol
An external method for users to purchase and mint NFTs. Requires that the sale is active, that the minted NFTs will not exceed the `MAX_SUPPLY`, and that a sufficient payable value is sent. amount The number of NFTs to mint./
function mint(uint256 amount) external payable { uint256 ts = totalSupply(); uint256 minted = _numberMinted(msg.sender); require(saleIsActive, "Sale must be active to mint tokens"); require(amount + minted <= walletLimit, "Exceeds wallet limit"); require(ts + amount <= MAX_SUPPLY, "Purchase would exceed max tokens"); require(currentPrice * amount == msg.value, "Value sent is not correct"); _safeMint(msg.sender, amount); }
9,382,004
// File: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/access/AccessControl.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/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/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/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/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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/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}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/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: @openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol pragma solidity ^0.8.0; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @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); } } // File: @openzeppelin/contracts/security/Pausable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol pragma solidity ^0.8.0; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // File: contracts/IERC2981.sol pragma solidity 0.8.6; // https://eips.ethereum.org/EIPS/eip-2981 /// @dev Interface for the NFT Royalty Standard interface IERC2981 { /** * @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 value - 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 _value sale price */ function royaltyInfo( uint256 tokenId, uint256 value ) external returns ( address receiver, uint256 royaltyAmount ); } // File: contracts/ERC2981.sol pragma solidity 0.8.6; abstract contract ERC2981 is ERC165, IERC2981 { function royaltyInfo( uint256 _tokenId, uint256 _value ) external virtual override returns ( address _receiver, uint256 _royaltyAmount ); function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } } // File: contracts/NFT.sol pragma solidity 0.8.6; contract NFT is AccessControl, ERC2981, ERC721Enumerable, ERC721Burnable, ERC721Pausable { event RoyaltyWalletChanged(address indexed previousWallet, address indexed newWallet); event RoyaltyFeeChanged(uint256 previousFee, uint256 newFee); event BaseURIChanged(string previousURI, string newURI); bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); uint256 public constant ROYALTY_FEE_DENOMINATOR = 100000; uint256 public royaltyFee; address public royaltyWallet; string private _baseTokenURI; /** * @param _name ERC721 token name * @param _symbol ERC721 token symbol * @param _uri Base token uri * @param _royaltyWallet Wallet where royalties should be sent * @param _royaltyFee Fee numerator to be used for fees */ constructor( string memory _name, string memory _symbol, string memory _uri, address _royaltyWallet, uint256 _royaltyFee ) ERC721(_name, _symbol) { _setBaseTokenURI(_uri); _setRoyaltyWallet(_royaltyWallet); _setRoyaltyFee(_royaltyFee); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OWNER_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); } /** * @dev Throws if called by any account other than owners. Implemented using the underlying AccessControl methods. */ modifier onlyOwners() { require(hasRole(OWNER_ROLE, _msgSender()), "Caller does not have the OWNER_ROLE"); _; } /** * @dev Throws if called by any account other than minters. Implemented using the underlying AccessControl methods. */ modifier onlyMinters() { require(hasRole(MINTER_ROLE, _msgSender()), "Caller does not have the MINTER_ROLE"); _; } /** * @dev Mints the specified token ids to the recipient addresses * @param recipient Address that will receive the tokens * @param tokenIds Array of tokenIds to be minted */ function mint(address recipient, uint256[] calldata tokenIds) external onlyMinters { for (uint256 i = 0; i < tokenIds.length; i++) { _mint(recipient, tokenIds[i]); } } /** * @dev Mints the specified token id to the recipient addresses * @dev The unused string parameter exists to support the API used by ChainBridge. * @param recipient Address that will receive the tokens * @param tokenId tokenId to be minted */ function mint(address recipient, uint256 tokenId, string calldata) external onlyMinters { _mint(recipient, tokenId); } /** * @dev Pauses token transfers */ function pause() external onlyOwners { _pause(); } /** * @dev Unpauses token transfers */ function unpause() external onlyOwners { _unpause(); } /** * @dev Sets the base token URI * @param uri Base token URI */ function setBaseTokenURI(string calldata uri) external onlyOwners { _setBaseTokenURI(uri); } /** * @dev Sets the wallet to which royalties should be sent * @param _royaltyWallet Address that should receive the royalties */ function setRoyaltyWallet(address _royaltyWallet) external onlyOwners { _setRoyaltyWallet(_royaltyWallet); } /** * @dev Sets the fee percentage for royalties * @param _royaltyFee Basis points to compute royalty percentage */ function setRoyaltyFee(uint256 _royaltyFee) external onlyOwners { _setRoyaltyFee(_royaltyFee); } /** * @dev Function defined by ERC2981, which provides information about fees. * @param value Price being paid for the token (in base units) */ function royaltyInfo( uint256, // tokenId is not used in this case as all tokens take the same fee uint256 value ) external view override returns ( address, // receiver uint256 // royaltyAmount ) { return (royaltyWallet, (value * royaltyFee) / ROYALTY_FEE_DENOMINATOR); } /** * @dev For each existing tokenId, it returns the URI where metadata is stored * @param tokenId Token id */ function tokenURI(uint256 tokenId) public view override returns (string memory) { string memory uri = super.tokenURI(tokenId); return bytes(uri).length > 0 ? string(abi.encodePacked(uri, ".json")) : ""; } function supportsInterface(bytes4 interfaceId) public view override(AccessControl, ERC2981, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function _setBaseTokenURI(string memory newURI) internal { emit BaseURIChanged(_baseTokenURI, newURI); _baseTokenURI = newURI; } function _setRoyaltyWallet(address _royaltyWallet) internal { require(_royaltyWallet != address(0), "INVALID_WALLET"); emit RoyaltyWalletChanged(royaltyWallet, _royaltyWallet); royaltyWallet = _royaltyWallet; } function _setRoyaltyFee(uint256 _royaltyFee) internal { require(_royaltyFee <= ROYALTY_FEE_DENOMINATOR, "INVALID_FEE"); emit RoyaltyFeeChanged(royaltyFee, _royaltyFee); royaltyFee = _royaltyFee; } function _baseURI() internal view override returns (string memory) { return _baseTokenURI; } }
Sets the wallet to which royalties should be sent _royaltyWallet Address that should receive the royalties/
function setRoyaltyWallet(address _royaltyWallet) external onlyOwners { _setRoyaltyWallet(_royaltyWallet); }
71,301
pragma solidity ^0.4.13; library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private rentrancy_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(!rentrancy_lock); rentrancy_lock = true; _; rentrancy_lock = false; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value); function approve(address spender, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } 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) { 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 uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) { var _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 behalf 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, uint256 _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) require(allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @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 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract Transmutable { function transmute(address to, uint256 value) returns (bool, uint256); event Transmuted(address indexed who, address baseContract, address transmutedContract, uint256 sourceQuantity, uint256 destQuantity); } // Contracts that can be transmuted to should implement this contract TransmutableInterface { function transmuted(uint256 _value) returns (bool, uint256); } contract ERC20Mineable is StandardToken, ReentrancyGuard { uint256 public constant divisible_units = 10000000; uint256 public constant decimals = 8; uint256 public constant initial_reward = 100; /** totalSupply in StandardToken refers to currently available supply * maximumSupply refers to the cap on mining. * When mining is finished totalSupply == maximumSupply */ uint256 public maximumSupply; // Current mining difficulty in Wei uint256 public currentDifficultyWei; // Minimum difficulty uint256 public minimumDifficultyThresholdWei; /** Block creation rate as number of Ethereum blocks per mining cycle * 10 minutes at 12 seconds a block would be an internal block * generated every 50 Ethereum blocks */ uint256 public blockCreationRate; /* difficultyAdjustmentPeriod should be every two weeks, or * 2016 internal blocks. */ uint256 public difficultyAdjustmentPeriod; /* When was the last time we did a difficulty adjustment. * In case mining ceases for indeterminate duration */ uint256 public lastDifficultyAdjustmentEthereumBlock; // Scale multiplier limit for difficulty adjustment uint256 public constant difficultyScaleMultiplierLimit = 4; // Total blocks mined helps us calculate the current reward uint256 public totalBlocksMined; // Reward adjustment period in Bitcoineum native blocks uint256 public rewardAdjustmentPeriod; // Total amount of Wei put into mining during current period uint256 public totalWeiCommitted; // Total amount of Wei expected for this mining period uint256 public totalWeiExpected; // Where to burn Ether address public burnAddress; /** Each block is created on a mining attempt if * it does not already exist. * this keeps track of the target difficulty at the time of creation */ struct InternalBlock { uint256 targetDifficultyWei; uint256 blockNumber; uint256 totalMiningWei; uint256 totalMiningAttempts; uint256 currentAttemptOffset; bool payed; address payee; bool isCreated; } /** Mining attempts are given a projected offset to minimize * keyspace overlap to increase fairness by reducing the redemption * race condition * This does not remove the possibility that two or more miners will * be competing for the same award, especially if subsequent increases in * wei from a single miner increase overlap */ struct MiningAttempt { uint256 projectedOffset; uint256 value; bool isCreated; } // Each guess gets assigned to a block mapping (uint256 => InternalBlock) public blockData; mapping (uint256 => mapping (address => MiningAttempt)) public miningAttempts; // Utility related function resolve_block_hash(uint256 _blockNum) public constant returns (bytes32) { return block.blockhash(_blockNum); } function current_external_block() public constant returns (uint256) { return block.number; } function external_to_internal_block_number(uint256 _externalBlockNum) public constant returns (uint256) { // blockCreationRate is > 0 return _externalBlockNum / blockCreationRate; } // For the test harness verification function get_internal_block_number() public constant returns (uint256) { return external_to_internal_block_number(current_external_block()); } // Initial state related /** Dapps need to grab the initial state of the contract * in order to properly initialize mining or tracking * this is a single atomic function for getting state * rather than scattering it across multiple public calls * also returns the current blocks parameters * or default params if it hasn't been created yet * This is only called externally */ function getContractState() external constant returns (uint256, // currentDifficultyWei uint256, // minimumDifficultyThresholdWei uint256, // blockNumber uint256, // blockCreationRate uint256, // difficultyAdjustmentPeriod uint256, // rewardAdjustmentPeriod uint256, // lastDifficultyAdustmentEthereumBlock uint256, // totalBlocksMined uint256, // totalWeiCommitted uint256, // totalWeiExpected uint256, // b.targetDifficultyWei uint256, // b.totalMiningWei uint256 // b.currentAttemptOffset ) { InternalBlock memory b; uint256 _blockNumber = external_to_internal_block_number(current_external_block()); if (!blockData[_blockNumber].isCreated) { b = InternalBlock( {targetDifficultyWei: currentDifficultyWei, blockNumber: _blockNumber, totalMiningWei: 0, totalMiningAttempts: 0, currentAttemptOffset: 0, payed: false, payee: 0, isCreated: true }); } else { b = blockData[_blockNumber]; } return (currentDifficultyWei, minimumDifficultyThresholdWei, _blockNumber, blockCreationRate, difficultyAdjustmentPeriod, rewardAdjustmentPeriod, lastDifficultyAdjustmentEthereumBlock, totalBlocksMined, totalWeiCommitted, totalWeiExpected, b.targetDifficultyWei, b.totalMiningWei, b.currentAttemptOffset); } function getBlockData(uint256 _blockNum) public constant returns (uint256, uint256, uint256, uint256, uint256, bool, address, bool) { InternalBlock memory iBlock = blockData[_blockNum]; return (iBlock.targetDifficultyWei, iBlock.blockNumber, iBlock.totalMiningWei, iBlock.totalMiningAttempts, iBlock.currentAttemptOffset, iBlock.payed, iBlock.payee, iBlock.isCreated); } function getMiningAttempt(uint256 _blockNum, address _who) public constant returns (uint256, uint256, bool) { if (miningAttempts[_blockNum][_who].isCreated) { return (miningAttempts[_blockNum][_who].projectedOffset, miningAttempts[_blockNum][_who].value, miningAttempts[_blockNum][_who].isCreated); } else { return (0, 0, false); } } // Mining Related modifier blockCreated(uint256 _blockNum) { require(blockData[_blockNum].isCreated); _; } modifier blockRedeemed(uint256 _blockNum) { require(_blockNum != current_external_block()); /* Should capture if the blockdata is payed * or if it does not exist in the blockData mapping */ require(blockData[_blockNum].isCreated); require(!blockData[_blockNum].payed); _; } modifier initBlock(uint256 _blockNum) { require(_blockNum != current_external_block()); if (!blockData[_blockNum].isCreated) { // This is a new block, adjust difficulty adjust_difficulty(); // Create new block for tracking blockData[_blockNum] = InternalBlock( {targetDifficultyWei: currentDifficultyWei, blockNumber: _blockNum, totalMiningWei: 0, totalMiningAttempts: 0, currentAttemptOffset: 0, payed: false, payee: 0, isCreated: true }); } _; } modifier isValidAttempt() { /* If the Ether for this mining attempt is less than minimum * 0.0000001 % of total difficulty */ uint256 minimum_wei = currentDifficultyWei / divisible_units; require (msg.value >= minimum_wei); /* Let's bound the value to guard against potential overflow * i.e max int, or an underflow bug * This is a single attempt */ require(msg.value <= (1000000 ether)); _; } modifier alreadyMined(uint256 blockNumber, address sender) { require(blockNumber != current_external_block()); /* We are only going to allow one mining attempt per block per account * This prevents stuffing and make it easier for us to track boundaries */ // This user already made a mining attempt for this block require(!checkMiningAttempt(blockNumber, sender)); _; } function checkMiningActive() public constant returns (bool) { return (totalSupply < maximumSupply); } modifier isMiningActive() { require(checkMiningActive()); _; } function burn(uint256 value) internal { /* We don't really care if the burn fails for some * weird reason. */ bool ret = burnAddress.send(value); /* If we cannot burn this ether, than the contract might * be under some kind of stack attack. * Even though it shouldn't matter, let's err on the side of * caution and throw in case there is some invalid state. */ require (ret); } event MiningAttemptEvent( address indexed _from, uint256 _value, uint256 indexed _blockNumber, uint256 _totalMinedWei, uint256 _targetDifficultyWei ); event LogEvent( string _info ); /** * @dev Add a mining attempt for the current internal block * Initialize an empty block if not created * Invalidate this mining attempt if the block has been paid out */ function mine() external payable nonReentrant isValidAttempt isMiningActive initBlock(external_to_internal_block_number(current_external_block())) blockRedeemed(external_to_internal_block_number(current_external_block())) alreadyMined(external_to_internal_block_number(current_external_block()), msg.sender) returns (bool) { /* Let's immediately adjust the difficulty * In case an abnormal period of time has elapsed * nobody has been mining etc. * Will let us recover the network even if the * difficulty spikes to some absurd amount * this should only happen on the first attempt on a block */ uint256 internalBlockNum = external_to_internal_block_number(current_external_block()); miningAttempts[internalBlockNum][msg.sender] = MiningAttempt({projectedOffset: blockData[internalBlockNum].currentAttemptOffset, value: msg.value, isCreated: true}); // Increment the mining attempts for this block blockData[internalBlockNum].totalMiningAttempts += 1; blockData[internalBlockNum].totalMiningWei += msg.value; totalWeiCommitted += msg.value; /* We are trying to stack mining attempts into their relative * positions in the key space. */ blockData[internalBlockNum].currentAttemptOffset += msg.value; MiningAttemptEvent(msg.sender, msg.value, internalBlockNum, blockData[internalBlockNum].totalMiningWei, blockData[internalBlockNum].targetDifficultyWei ); // All mining attempt Ether is burned burn(msg.value); return true; } // Redemption Related modifier userMineAttempted(uint256 _blockNum, address _user) { require(checkMiningAttempt(_blockNum, _user)); _; } modifier isBlockMature(uint256 _blockNumber) { require(_blockNumber != current_external_block()); require(checkBlockMature(_blockNumber, current_external_block())); require(checkRedemptionWindow(_blockNumber, current_external_block())); _; } // Just in case this block falls outside of the available // block range, possibly because of a change in network params modifier isBlockReadable(uint256 _blockNumber) { InternalBlock memory iBlock = blockData[_blockNumber]; uint256 targetBlockNum = targetBlockNumber(_blockNumber); require(resolve_block_hash(targetBlockNum) != 0); _; } function calculate_difficulty_attempt(uint256 targetDifficultyWei, uint256 totalMiningWei, uint256 value) public constant returns (uint256) { // The total amount of Wei sent for this mining attempt exceeds the difficulty level // So the calculation of percentage keyspace should be done on the total wei. uint256 selectedDifficultyWei = 0; if (totalMiningWei > targetDifficultyWei) { selectedDifficultyWei = totalMiningWei; } else { selectedDifficultyWei = targetDifficultyWei; } /* normalize the value against the entire key space * Multiply it out because we do not have floating point * 10000000 is .0000001 % increments */ uint256 intermediate = ((value * divisible_units) / selectedDifficultyWei); uint256 max_int = 0; // Underflow to maxint max_int = max_int - 1; if (intermediate >= divisible_units) { return max_int; } else { return intermediate * (max_int / divisible_units); } } function calculate_range_attempt(uint256 difficulty, uint256 offset) public constant returns (uint256, uint256) { /* Both the difficulty and offset should be normalized * against the difficulty scale. * If they are not we might have an integer overflow */ require(offset + difficulty >= offset); return (offset, offset+difficulty); } // Total allocated reward is proportional to burn contribution to limit incentive for // hash grinding attacks function calculate_proportional_reward(uint256 _baseReward, uint256 _userContributionWei, uint256 _totalCommittedWei) public constant returns (uint256) { require(_userContributionWei <= _totalCommittedWei); require(_userContributionWei > 0); require(_totalCommittedWei > 0); uint256 intermediate = ((_userContributionWei * divisible_units) / _totalCommittedWei); if (intermediate >= divisible_units) { return _baseReward; } else { return intermediate * (_baseReward / divisible_units); } } function calculate_base_mining_reward(uint256 _totalBlocksMined) public constant returns (uint256) { /* Block rewards starts at initial_reward * Every 10 minutes * Block reward decreases by 50% every 210000 blocks */ uint256 mined_block_period = 0; if (_totalBlocksMined < 210000) { mined_block_period = 210000; } else { mined_block_period = _totalBlocksMined; } // Again we have to do this iteratively because of floating // point limitations in solidity. uint256 total_reward = initial_reward * (10 ** decimals); uint256 i = 1; uint256 rewardperiods = mined_block_period / 210000; if (mined_block_period % 210000 > 0) { rewardperiods += 1; } for (i=1; i < rewardperiods; i++) { total_reward = total_reward / 2; } return total_reward; } // Break out the expected wei calculation // for easy external testing function calculate_next_expected_wei(uint256 _totalWeiCommitted, uint256 _totalWeiExpected, uint256 _minimumDifficultyThresholdWei, uint256 _difficultyScaleMultiplierLimit) public constant returns (uint256) { /* The adjustment window has been fulfilled * The new difficulty should be bounded by the total wei actually spent * capped at difficultyScaleMultiplierLimit times */ uint256 lowerBound = _totalWeiExpected / _difficultyScaleMultiplierLimit; uint256 upperBound = _totalWeiExpected * _difficultyScaleMultiplierLimit; if (_totalWeiCommitted < lowerBound) { _totalWeiExpected = lowerBound; } else if (_totalWeiCommitted > upperBound) { _totalWeiExpected = upperBound; } else { _totalWeiExpected = _totalWeiCommitted; } /* If difficulty drops too low lets set it to our minimum. * This may halt coin creation, but obviously does not affect * token transactions. */ if (_totalWeiExpected < _minimumDifficultyThresholdWei) { _totalWeiExpected = _minimumDifficultyThresholdWei; } return _totalWeiExpected; } function adjust_difficulty() internal { /* Total blocks mined might not be increasing if the * difficulty is too high. So we should instead base the adjustment * on the progression of the Ethereum network. * So that the difficulty can increase/deflate regardless of sparse * mining attempts */ if ((current_external_block() - lastDifficultyAdjustmentEthereumBlock) > (difficultyAdjustmentPeriod * blockCreationRate)) { // Get the new total wei expected via static function totalWeiExpected = calculate_next_expected_wei(totalWeiCommitted, totalWeiExpected, minimumDifficultyThresholdWei * difficultyAdjustmentPeriod, difficultyScaleMultiplierLimit); currentDifficultyWei = totalWeiExpected / difficultyAdjustmentPeriod; // Regardless of difficulty adjustment, let us zero totalWeiCommited totalWeiCommitted = 0; // Lets reset the difficulty adjustment block target lastDifficultyAdjustmentEthereumBlock = current_external_block(); } } event BlockClaimedEvent( address indexed _from, address indexed _forCreditTo, uint256 _reward, uint256 indexed _blockNumber ); modifier onlyWinner(uint256 _blockNumber) { require(checkWinning(_blockNumber)); _; } // Helper function to avoid stack issues function calculate_reward(uint256 _totalBlocksMined, address _sender, uint256 _blockNumber) public constant returns (uint256) { return calculate_proportional_reward(calculate_base_mining_reward(_totalBlocksMined), miningAttempts[_blockNumber][_sender].value, blockData[_blockNumber].totalMiningWei); } /** * @dev Claim the mining reward for a given block * @param _blockNumber The internal block that the user is trying to claim * @param forCreditTo When the miner account is different from the account * where we want to deliver the redeemed Bitcoineum. I.e Hard wallet. */ function claim(uint256 _blockNumber, address forCreditTo) nonReentrant blockRedeemed(_blockNumber) isBlockMature(_blockNumber) isBlockReadable(_blockNumber) userMineAttempted(_blockNumber, msg.sender) onlyWinner(_blockNumber) external returns (bool) { /* If attempt is valid, invalidate redemption * Difficulty is adjusted here * and on bidding, in case bidding stalls out for some * unusual period of time. * Do everything, then adjust supply and balance */ blockData[_blockNumber].payed = true; blockData[_blockNumber].payee = msg.sender; totalBlocksMined = totalBlocksMined + 1; uint256 proportional_reward = calculate_reward(totalBlocksMined, msg.sender, _blockNumber); balances[forCreditTo] = balances[forCreditTo].add(proportional_reward); totalSupply += proportional_reward; BlockClaimedEvent(msg.sender, forCreditTo, proportional_reward, _blockNumber); // Mining rewards should show up as ERC20 transfer events // So that ERC20 scanners will see token creation. Transfer(this, forCreditTo, proportional_reward); return true; } /** * @dev Claim the mining reward for a given block * @param _blockNum The internal block that the user is trying to claim */ function isBlockRedeemed(uint256 _blockNum) constant public returns (bool) { if (!blockData[_blockNum].isCreated) { return false; } else { return blockData[_blockNum].payed; } } /** * @dev Get the target block in the winning equation * @param _blockNum is the internal block number to get the target block for */ function targetBlockNumber(uint256 _blockNum) constant public returns (uint256) { return ((_blockNum + 1) * blockCreationRate); } /** * @dev Check whether a given block is mature * @param _blockNum is the internal block number to check */ function checkBlockMature(uint256 _blockNum, uint256 _externalblock) constant public returns (bool) { return (_externalblock >= targetBlockNumber(_blockNum)); } /** * @dev Check the redemption window for a given block * @param _blockNum is the internal block number to check */ function checkRedemptionWindow(uint256 _blockNum, uint256 _externalblock) constant public returns (bool) { uint256 _targetblock = targetBlockNumber(_blockNum); return _externalblock >= _targetblock && _externalblock < (_targetblock + 256); } /** * @dev Check whether a mining attempt was made by sender for this block * @param _blockNum is the internal block number to check */ function checkMiningAttempt(uint256 _blockNum, address _sender) constant public returns (bool) { return miningAttempts[_blockNum][_sender].isCreated; } /** * @dev Did the user win a specific block and can claim it? * @param _blockNum is the internal block number to check */ function checkWinning(uint256 _blockNum) constant public returns (bool) { if (checkMiningAttempt(_blockNum, msg.sender) && checkBlockMature(_blockNum, current_external_block())) { InternalBlock memory iBlock = blockData[_blockNum]; uint256 targetBlockNum = targetBlockNumber(iBlock.blockNumber); MiningAttempt memory attempt = miningAttempts[_blockNum][msg.sender]; uint256 difficultyAttempt = calculate_difficulty_attempt(iBlock.targetDifficultyWei, iBlock.totalMiningWei, attempt.value); uint256 beginRange; uint256 endRange; uint256 targetBlockHashInt; (beginRange, endRange) = calculate_range_attempt(difficultyAttempt, calculate_difficulty_attempt(iBlock.targetDifficultyWei, iBlock.totalMiningWei, attempt.projectedOffset)); targetBlockHashInt = uint256(keccak256(resolve_block_hash(targetBlockNum))); // This is the winning condition if ((beginRange < targetBlockHashInt) && (endRange >= targetBlockHashInt)) { return true; } } return false; } } contract Bitcoineum is ERC20Mineable, Transmutable { string public constant name = "Bitcoineum"; string public constant symbol = "BTE"; uint256 public constant decimals = 8; uint256 public constant INITIAL_SUPPLY = 0; // 21 Million coins at 8 decimal places uint256 public constant MAX_SUPPLY = 21000000 * (10**8); function Bitcoineum() { totalSupply = INITIAL_SUPPLY; maximumSupply = MAX_SUPPLY; // 0.0001 Ether per block // Difficulty is so low because it doesn't include // gas prices for execution currentDifficultyWei = 100 szabo; minimumDifficultyThresholdWei = 100 szabo; // Ethereum blocks to internal blocks // Roughly 10 minute windows blockCreationRate = 50; // Adjust difficulty x claimed internal blocks difficultyAdjustmentPeriod = 2016; // Reward adjustment rewardAdjustmentPeriod = 210000; // This is the effective block counter, since block windows are discontinuous totalBlocksMined = 0; totalWeiExpected = difficultyAdjustmentPeriod * currentDifficultyWei; // Balance of this address can be used to determine total burned value // not including fees spent. burnAddress = 0xdeaDDeADDEaDdeaDdEAddEADDEAdDeadDEADDEaD; lastDifficultyAdjustmentEthereumBlock = block.number; } /** * @dev Bitcoineum can extend proof of burn into convertable units * that have token specific properties * @param to is the address of the contract that Bitcoineum is converting into * @param value is the quantity of Bitcoineum to attempt to convert */ function transmute(address to, uint256 value) nonReentrant returns (bool, uint256) { require(value > 0); require(balances[msg.sender] >= value); require(totalSupply >= value); balances[msg.sender] = balances[msg.sender].sub(value); totalSupply = totalSupply.sub(value); TransmutableInterface target = TransmutableInterface(to); bool _result = false; uint256 _total = 0; (_result, _total) = target.transmuted(value); require (_result); Transmuted(msg.sender, this, to, value, _total); return (_result, _total); } }
Let's immediately adjust the difficulty In case an abnormal period of time has elapsed nobody has been mining etc. Will let us recover the network even if the difficulty spikes to some absurd amount this should only happen on the first attempt on a block/
function mine() external payable nonReentrant isValidAttempt isMiningActive initBlock(external_to_internal_block_number(current_external_block())) blockRedeemed(external_to_internal_block_number(current_external_block())) alreadyMined(external_to_internal_block_number(current_external_block()), msg.sender) returns (bool) { uint256 internalBlockNum = external_to_internal_block_number(current_external_block()); miningAttempts[internalBlockNum][msg.sender] = MiningAttempt({projectedOffset: blockData[internalBlockNum].currentAttemptOffset, value: msg.value, isCreated: true}); blockData[internalBlockNum].totalMiningWei += msg.value; totalWeiCommitted += msg.value; MiningAttemptEvent(msg.sender, msg.value, internalBlockNum, blockData[internalBlockNum].totalMiningWei, blockData[internalBlockNum].targetDifficultyWei ); return true; }
2,478,592
pragma solidity ^0.4.24; contract Stuff { struct stuffInfo{ uint code; string name; string description; uint cost; address owner; bool isBuy; } mapping(uint=> stuffInfo) public stuffArray; mapping(address=> stuffInfo[]) public personal; uint public num; uint public subnum; event StuffInfo(uint code, string name,string description, uint cost, address owner, bool isBuy); constructor() public { num=0; } // Adopting a pets function buy(address buyer, uint stuffCode) public returns(bool success) { require(stuffArray[stuffCode].isBuy==false); stuffArray[stuffCode].owner=msg.sender; //존재 하는지 비교 stuffArray[stuffCode].isBuy=true; // 물건 구매 했다고 표시 personal[buyer].push(stuffArray[stuffCode]); //개인 구매 물건에 추가 emit StuffInfo(stuffArray[stuffCode].code, stuffArray[stuffCode].name,stuffArray[stuffCode].description, stuffArray[stuffCode].cost, buyer,stuffArray[stuffCode].isBuy); return true; } function registerStuff(address _owner, string _name, string _description, uint _cost) public returns(bool success){ // stuffInfo memory tmp= stuffInfo(num,_name,_description,_cost,_owner,false); stuffArray[num]=stuffInfo(num,_name,_description,_cost,_owner,false); num+=1; return true; } function deleteStuff(uint _code, address _owner ) public returns(bool success) { require(stuffArray[_code].owner ==_owner); require(stuffArray[_code].code ==_code); delete stuffArray[_code]; subnum+=1; return true; } function getStuff(uint id) public view returns(uint, string , string , uint ,address , bool ){ stuffInfo memory tmp=stuffArray[id]; return (tmp.code,tmp.name, tmp.description,tmp.cost,tmp.owner,tmp.isBuy); } function getnum() public view returns( uint,uint){ return (num, subnum); } function getPersonal(address addr)public view returns(uint){ return personal[addr].length; } function getPersonalStuff(address addr, uint id) public view returns(uint, string , string , uint ,address , bool ){ stuffInfo memory tmp=personal[addr][id]; return (tmp.code,tmp.name, tmp.description,tmp.cost,tmp.owner,tmp.isBuy); } }
stuffInfo memory tmp= stuffInfo(num,_name,_description,_cost,_owner,false);
function registerStuff(address _owner, string _name, string _description, uint _cost) public returns(bool success){ stuffArray[num]=stuffInfo(num,_name,_description,_cost,_owner,false); num+=1; return true; }
5,440,081
pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/cryptography/ECDSA.sol"; import "./AccountRegistry.sol"; contract ComplianceToken{ using SafeMath for uint256; using ECDSA for bytes32; mapping(address => uint256) private _balance; address private _issuer; uint256 private _totalSupply; AccountRegistry private _accountRegistry; event Keccak256(bytes message, bytes32 hash); event EthMsgHash(bytes32 hash, bytes32 msgHash); event DumpAccountRegistry(address addr); event DumpTrustedAccount(address addr, bool); event DumpCommonAccount(address addr, bool, address bankAddr); constructor(address regAddr) public { require(regAddr != address(0)); _issuer = msg.sender; _totalSupply = 1000000; _balance[_issuer] = _totalSupply; _accountRegistry = AccountRegistry(regAddr); } function getAccountRegistry() public view returns(address) { return address(_accountRegistry); } // Admin 或者 Bank 可以直接转账 function trustedTransfer(address recipient, uint256 amount) public { require(recipient != address(0), "ERC20: transfer to the zero address"); require( _accountRegistry.isAccountTrusted(msg.sender) ); doTransfer(msg.sender, recipient, amount); } // 转账 function transfer(address payer, address recipient, uint256 amount, bytes memory signature) public { // 检查转账规则 // payer 与 recipient 的地址是已经注册过的 require(_accountRegistry.getAccountType(payer) != AccountRegistry.AccountType.None); require(_accountRegistry.getBankAccount(payer) == msg.sender); require(_accountRegistry.getAccountType(recipient) != AccountRegistry.AccountType.None); address recoverAddr = recoverSign(recipient, amount, signature); // 检查交易 payer 的签名 require(payer == recoverAddr); doTransfer(payer, recipient, amount); } function doTransfer(address payer, address recipient, uint256 amount) internal { // 检查 payer 的余额 require(_balance[payer] >= amount); // TODO: 优化转账的语法,优化数学运算的语法 _balance[payer] = _balance[payer].sub(amount); _balance[recipient] = _balance[recipient].add(amount); } // 查询余额 function balanceOf(address addr) public view returns (uint256) { return _balance[addr]; } function recoverSign(address recipient, uint256 amount, bytes memory signature) public pure returns(address){ bytes32 msghash = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n64", uint256(recipient), amount)); address result = msghash.recover(signature); return result; } function testHash(address recipient, uint256 amount) public { bytes32 hash = keccak256(abi.encodePacked(uint256(recipient), amount)); emit Keccak256(abi.encodePacked(uint256(recipient), amount), hash); bytes32 msghash = hash.toEthSignedMessageHash(); emit EthMsgHash(hash, msghash); } function dump(address mgAddr, address citiAddr, address aliceAddr, address bobAddr) public { // AccountRegistry address emit DumpAccountRegistry(address(_accountRegistry)); // MG and Citi infor emit DumpTrustedAccount(mgAddr, _accountRegistry.isAccountTrusted(mgAddr)); emit DumpTrustedAccount(citiAddr, _accountRegistry.isAccountTrusted(citiAddr)); // Alice and Bob infor emit DumpCommonAccount(aliceAddr, _accountRegistry.isAccountTrusted(aliceAddr), _accountRegistry.getBankAccount(aliceAddr)); emit DumpCommonAccount(bobAddr, _accountRegistry.isAccountTrusted(bobAddr), _accountRegistry.getBankAccount(bobAddr)); } }
AccountRegistry address MG and Citi infor Alice and Bob infor
function dump(address mgAddr, address citiAddr, address aliceAddr, address bobAddr) public { emit DumpAccountRegistry(address(_accountRegistry)); emit DumpTrustedAccount(mgAddr, _accountRegistry.isAccountTrusted(mgAddr)); emit DumpTrustedAccount(citiAddr, _accountRegistry.isAccountTrusted(citiAddr)); emit DumpCommonAccount(aliceAddr, _accountRegistry.isAccountTrusted(aliceAddr), _accountRegistry.getBankAccount(aliceAddr)); emit DumpCommonAccount(bobAddr, _accountRegistry.isAccountTrusted(bobAddr), _accountRegistry.getBankAccount(bobAddr)); }
1,082,252
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/helpers/BalancerErrors.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ERC20Helpers.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-pool-utils/contracts/LegacyBasePool.sol"; import "@balancer-labs/v2-pool-utils/contracts/interfaces/IRateProvider.sol"; import "@balancer-labs/v2-pool-utils/contracts/rates/PriceRateCache.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IGeneralPool.sol"; import "./LinearMath.sol"; import "./LinearPoolUserData.sol"; /** * @dev Linear Pools are designed to hold two assets: "main" and "wrapped" tokens that have an equal value underlying * token (e.g., DAI and waDAI). There must be an external feed available to provide an exact, non-manipulable exchange * rate between the tokens. In particular, any reversible manipulation (e.g. causing the rate to increase and then * decrease) can lead to severe issues and loss of funds. * * The Pool will register three tokens in the Vault however: the two assets and the BPT itself, * so that BPT can be exchanged (effectively joining and exiting) via swaps. * * Despite inheriting from BasePool, much of the basic behavior changes. This Pool does not support regular joins and * exits, as the entire BPT supply is 'preminted' during initialization. * * Unlike most other Pools, this one does not attempt to create revenue by charging fees: value is derived by holding * the wrapped, yield-bearing asset. However, the 'swap fee percentage' value is still used, albeit with a different * meaning. This Pool attempts to hold a certain amount of "main" tokens, between a lower and upper target value. * The pool charges fees on trades that move the balance outside that range, which are then paid back as incentives to * traders whose swaps return the balance to the desired region. * The net revenue via fees is expected to be zero: all collected fees are used to pay for this 'rebalancing'. */ abstract contract LinearPool is LegacyBasePool, IGeneralPool, IRateProvider { using WordCodec for bytes32; using FixedPoint for uint256; using PriceRateCache for bytes32; using LinearPoolUserData for bytes; uint256 private constant _TOTAL_TOKENS = 3; // Main token, wrapped token, BPT // This is the maximum token amount the Vault can hold. In regular operation, the total BPT supply remains constant // and equal to _INITIAL_BPT_SUPPLY, but most of it remains in the Pool, waiting to be exchanged for tokens. The // actual amount of BPT in circulation is the total supply minus the amount held by the Pool, and is known as the // 'virtual supply'. // The total supply can only change if the emergency pause is activated by governance, enabling an // alternative proportional exit that burns BPT. As this is not expected to happen, we optimize for // success by using _INITIAL_BPT_SUPPLY instead of totalSupply(), saving a storage read. This optimization is only // valid if the Pool is never paused: in case of an emergency that leads to burned tokens, the Pool should not // be used after the buffer period expires and it automatically 'unpauses'. uint256 private constant _INITIAL_BPT_SUPPLY = 2**(112) - 1; IERC20 private immutable _mainToken; IERC20 private immutable _wrappedToken; // The indices of each token when registered, which can then be used to access the balances array. uint256 private immutable _bptIndex; uint256 private immutable _mainIndex; uint256 private immutable _wrappedIndex; // Both BPT and the main token have a regular, constant scaling factor (equal to FixedPoint.ONE for BPT, and // dependent on the number of decimals for the main token). However, the wrapped token's scaling factor has two // components: the usual token decimal scaling factor, and an externally provided rate used to convert wrapped // tokens to an equivalent main token amount. This external rate is expected to be ever increasing, reflecting the // fact that the wrapped token appreciates in value over time (e.g. because it is accruing interest). uint256 private immutable _scalingFactorMainToken; uint256 private immutable _scalingFactorWrappedToken; // The lower and upper target are in BasePool's misc data field, which has 192 bits available (as it shares the same // storage slot as the swap fee percentage, which is 64 bits). These are already scaled by the main token's scaling // factor, which means that the maximum upper target is ~80 billion in the main token units if the token were to // have 18 decimals (2^(192/2) / 10^18), which is more than enough. // [ 64 bits | 96 bits | 96 bits ] // [ reserved | upper target | lower target ] // [ base pool swap fee | misc data ] // [ MSB LSB ] uint256 private constant _LOWER_TARGET_OFFSET = 0; uint256 private constant _UPPER_TARGET_OFFSET = 96; uint256 private constant _MAX_UPPER_TARGET = 2**(96) - 1; event TargetsSet(IERC20 indexed token, uint256 lowerTarget, uint256 upperTarget); constructor( IVault vault, string memory name, string memory symbol, IERC20 mainToken, IERC20 wrappedToken, uint256 upperTarget, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) LegacyBasePool( vault, IVault.PoolSpecialization.GENERAL, name, symbol, _sortTokens(mainToken, wrappedToken, this), new address[](_TOTAL_TOKENS), swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // Set tokens _mainToken = mainToken; _wrappedToken = wrappedToken; // Set token indexes (uint256 mainIndex, uint256 wrappedIndex, uint256 bptIndex) = _getSortedTokenIndexes( mainToken, wrappedToken, this ); _bptIndex = bptIndex; _mainIndex = mainIndex; _wrappedIndex = wrappedIndex; // Set scaling factors _scalingFactorMainToken = _computeScalingFactor(mainToken); _scalingFactorWrappedToken = _computeScalingFactor(wrappedToken); // Set initial targets. Lower target must be set to zero because initially there are no fees accumulated. // Otherwise the pool will owe fees at start which results in a manipulable rate. uint256 lowerTarget = 0; _setTargets(mainToken, lowerTarget, upperTarget); } function getMainToken() public view returns (address) { return address(_mainToken); } function getWrappedToken() public view returns (address) { return address(_wrappedToken); } function getBptIndex() external view returns (uint256) { return _bptIndex; } function getMainIndex() external view returns (uint256) { return _mainIndex; } function getWrappedIndex() external view returns (uint256) { return _wrappedIndex; } /** * @dev Finishes initialization of the Linear Pool: it is unusable before calling this function as no BPT will have * been minted. * * Since Linear Pools have preminted BPT stored in the Vault, they require an initial join to deposit said BPT as * their balance. Unfortunately, this cannot be performed during construction, as a join involves calling the * `onJoinPool` function on the Pool, and the Pool will not have any code until construction finishes. Therefore, * this must happen in a separate call. * * It is highly recommended to create Linear pools using the LinearPoolFactory, which calls `initialize` * automatically. */ function initialize() external { bytes32 poolId = getPoolId(); (IERC20[] memory tokens, , ) = getVault().getPoolTokens(poolId); // Joins typically involve the Pool receiving tokens in exchange for newly-minted BPT. In this case however, the // Pool will mint the entire BPT supply to itself, and join itself with it. uint256[] memory maxAmountsIn = new uint256[](_TOTAL_TOKENS); maxAmountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; // The first time this executes, it will call `_onInitializePool` (as the BPT supply will be zero). Future calls // will be routed to `_onJoinPool`, which always reverts, meaning `initialize` will only execute once. IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest({ assets: _asIAsset(tokens), maxAmountsIn: maxAmountsIn, userData: "", fromInternalBalance: false }); getVault().joinPool(poolId, address(this), address(this), request); } /** * @dev Implementation of onSwap, from IGeneralPool. */ function onSwap( SwapRequest memory request, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) public view override onlyVault(request.poolId) whenNotPaused returns (uint256) { // In most Pools, swaps involve exchanging one token held by the Pool for another. In this case however, since // one of the three tokens is the BPT itself, a swap might also be a join (main/wrapped for BPT) or an exit // (BPT for main/wrapped). // All three swap types (swaps, joins and exits) are fully disabled if the emergency pause is enabled. Under // these circumstances, the Pool should be exited using the regular Vault.exitPool function. // Sanity check: this is not entirely necessary as the Vault's interface enforces the indices to be valid, but // the check is cheap to perform. _require(indexIn < _TOTAL_TOKENS && indexOut < _TOTAL_TOKENS, Errors.OUT_OF_BOUNDS); // Note that we already know the indices of the main token, wrapped token and BPT, so there is no need to pass // these indices to the inner functions. // Upscale balances by the scaling factors (taking into account the wrapped token rate) uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); if (request.kind == IVault.SwapKind.GIVEN_IN) { // The amount given is for token in, the amount calculated is for token out request.amount = _upscale(request.amount, scalingFactors[indexIn]); uint256 amountOut = _onSwapGivenIn(request, balances, params); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactors[indexOut]); } else { // The amount given is for token out, the amount calculated is for token in request.amount = _upscale(request.amount, scalingFactors[indexOut]); uint256 amountIn = _onSwapGivenOut(request, balances, params); // amountIn tokens are entering the Pool, so we round up. return _downscaleUp(amountIn, scalingFactors[indexIn]); } } function _onSwapGivenIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenIn == this) { return _swapGivenBptIn(request, balances, params); } else if (request.tokenIn == _mainToken) { return _swapGivenMainIn(request, balances, params); } else if (request.tokenIn == _wrappedToken) { return _swapGivenWrappedIn(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenOut == _mainToken ? LinearMath._calcMainOutPerBptIn : LinearMath._calcWrappedOutPerBptIn)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _wrappedToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerMainIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedOutPerMainIn(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerWrappedIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainOutPerWrappedIn(request.amount, balances[_mainIndex], params); } function _onSwapGivenOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenOut == this) { return _swapGivenBptOut(request, balances, params); } else if (request.tokenOut == _mainToken) { return _swapGivenMainOut(request, balances, params); } else if (request.tokenOut == _wrappedToken) { return _swapGivenWrappedOut(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenIn == _mainToken ? LinearMath._calcMainInPerBptOut : LinearMath._calcWrappedInPerBptOut)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _wrappedToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerMainOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedInPerMainOut(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerWrappedOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainInPerWrappedOut(request.amount, balances[_mainIndex], params); } function _onInitializePool( bytes32, address sender, address recipient, uint256[] memory, bytes memory ) internal view override whenNotPaused returns (uint256, uint256[] memory) { // Linear Pools can only be initialized by the Pool performing the initial join via the `initialize` function. _require(sender == address(this), Errors.INVALID_INITIALIZATION); _require(recipient == address(this), Errors.INVALID_INITIALIZATION); // The full BPT supply will be minted and deposited in the Pool. Note that there is no need to approve the Vault // as it already has infinite BPT allowance. uint256 bptAmountOut = _INITIAL_BPT_SUPPLY; uint256[] memory amountsIn = new uint256[](_TOTAL_TOKENS); amountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; return (bptAmountOut, amountsIn); } function _onJoinPool( bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory ) internal pure override returns ( uint256, uint256[] memory, uint256[] memory ) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256, uint256[] memory, bytes memory userData ) internal view override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits typically revert, except for the proportional exit when the emergency pause mechanism has been // triggered. This allows for a simple and safe way to exit the Pool. // Note that the rate cache will not be automatically updated in such a scenario (though this can be still done // manually). This however should not lead to any issues as the rate is not important during the emergency exit. // On the contrary, decoupling the rate provider from the emergency exit might be useful under these // circumstances. LinearPoolUserData.ExitKind kind = userData.exitKind(); if (kind != LinearPoolUserData.ExitKind.EMERGENCY_EXACT_BPT_IN_FOR_TOKENS_OUT) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } else { _ensurePaused(); // Note that this will cause the user's BPT to be burned, which is not something that happens during // regular operation of this Pool, and may lead to accounting errors. Because of this, it is highly // advisable to stop using a Pool after it is paused and the pause window expires. (bptAmountIn, amountsOut) = _emergencyProportionalExit(balances, userData); // Due protocol fees are set to zero as this Pool accrues no fees and pays no protocol fees. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } } function _emergencyProportionalExit(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This proportional exit function is only enabled if the contract is paused, to provide users a way to // retrieve their tokens in case of an emergency. // // This particular exit function is the only one available because it is the simplest, and therefore least // likely to be incorrect, or revert and lock funds. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. // This process burns BPT, rendering `_getApproximateVirtualSupply` inaccurate, so we use the real method here uint256[] memory amountsOut = LinearMath._calcTokensOutGivenExactBptIn( balances, bptAmountIn, _getVirtualSupply(balances[_bptIndex]), _bptIndex ); return (bptAmountIn, amountsOut); } function _getMaxTokens() internal pure override returns (uint256) { return _TOTAL_TOKENS; } function _getMinimumBpt() internal pure override returns (uint256) { // Linear Pools don't lock any BPT, as the total supply will already be forever non-zero due to the preminting // mechanism, ensuring initialization only occurs once. return 0; } function _getTotalTokens() internal view virtual override returns (uint256) { return _TOTAL_TOKENS; } function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { if (token == _mainToken) { return _scalingFactorMainToken; } else if (token == _wrappedToken) { // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token // increases in value. return _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); } else if (token == this) { return FixedPoint.ONE; } else { _revert(Errors.INVALID_TOKEN); } } function _scalingFactors() internal view virtual override returns (uint256[] memory) { uint256[] memory scalingFactors = new uint256[](_TOTAL_TOKENS); // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token increases in // value. scalingFactors[_mainIndex] = _scalingFactorMainToken; scalingFactors[_wrappedIndex] = _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); scalingFactors[_bptIndex] = FixedPoint.ONE; return scalingFactors; } // Price rates /** * @dev For a Linear Pool, the rate represents the appreciation of BPT with respect to the underlying tokens. This * rate increases slowly as the wrapped token appreciates in value. */ function getRate() external view override returns (uint256) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); _upscaleArray(balances, _scalingFactors()); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); uint256 totalBalance = LinearMath._calcInvariant( LinearMath._toNominal(balances[_mainIndex], params), balances[_wrappedIndex] ); // Note that we're dividing by the virtual supply, which may be zero (causing this call to revert). However, the // only way for that to happen would be for all LPs to exit the Pool, and nothing prevents new LPs from // joining it later on. return totalBalance.divUp(_getApproximateVirtualSupply(balances[_bptIndex])); } function getWrappedTokenRate() external view returns (uint256) { return _getWrappedTokenRate(); } /** * @dev Should be 1e18 for the subsequent calculation of the wrapper token scaling factor. */ function _getWrappedTokenRate() internal view virtual returns (uint256); function getTargets() public view returns (uint256 lowerTarget, uint256 upperTarget) { bytes32 miscData = _getMiscData(); lowerTarget = miscData.decodeUint96(_LOWER_TARGET_OFFSET); upperTarget = miscData.decodeUint96(_UPPER_TARGET_OFFSET); } function _setTargets( IERC20 mainToken, uint256 lowerTarget, uint256 upperTarget ) private { _require(lowerTarget <= upperTarget, Errors.LOWER_GREATER_THAN_UPPER_TARGET); _require(upperTarget <= _MAX_UPPER_TARGET, Errors.UPPER_TARGET_TOO_HIGH); // Pack targets as two uint96 values into a single storage slot. This results in targets being capped to 96 // bits, but that should be more than enough. _setMiscData( WordCodec.encodeUint(lowerTarget, _LOWER_TARGET_OFFSET) | WordCodec.encodeUint(upperTarget, _UPPER_TARGET_OFFSET) ); emit TargetsSet(mainToken, lowerTarget, upperTarget); } function setTargets(uint256 newLowerTarget, uint256 newUpperTarget) external authenticate { // For a new target range to be valid: // - the pool must currently be between the current targets (meaning no fees are currently pending) // - the pool must currently be between the new targets (meaning setting them does not cause for fees to be // pending) // // The first requirement could be relaxed, as the LPs actually benefit from the pending fees not being paid out, // but being stricter makes analysis easier at little expense. (uint256 currentLowerTarget, uint256 currentUpperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(currentLowerTarget, currentUpperTarget), Errors.OUT_OF_TARGET_RANGE); _require(_isMainBalanceWithinTargets(newLowerTarget, newUpperTarget), Errors.OUT_OF_NEW_TARGET_RANGE); _setTargets(_mainToken, newLowerTarget, newUpperTarget); } function setSwapFeePercentage(uint256 swapFeePercentage) public override { // For the swap fee percentage to be changeable: // - the pool must currently be between the current targets (meaning no fees are currently pending) // // As the amount of accrued fees is not explicitly stored but rather derived from the main token balance and the // current swap fee percentage, requiring for no fees to be pending prevents the fee setter from changing the // amount of pending fees, which they could use to e.g. drain Pool funds in the form of inflated fees. (uint256 lowerTarget, uint256 upperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(lowerTarget, upperTarget), Errors.OUT_OF_TARGET_RANGE); super.setSwapFeePercentage(swapFeePercentage); } function _isMainBalanceWithinTargets(uint256 lowerTarget, uint256 upperTarget) private view returns (bool) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); uint256 mainTokenBalance = _upscale(balances[_mainIndex], _scalingFactor(_mainToken)); return mainTokenBalance >= lowerTarget && mainTokenBalance <= upperTarget; } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return actionId == getActionId(this.setTargets.selector) || super._isOwnerOnlyAction(actionId); } /** * @dev Returns the number of tokens in circulation. * * In other pools, this would be the same as `totalSupply`, but since this pool pre-mints all BPT, `totalSupply` * remains constant, whereas `virtualSupply` increases as users join the pool and decreases as they exit it. */ function getVirtualSupply() external view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // We technically don't need to upscale the BPT balance as its scaling factor is equal to one (since BPT has // 18 decimals), but we do it for completeness. uint256 bptBalance = _upscale(balances[_bptIndex], _scalingFactor(this)); return _getVirtualSupply(bptBalance); } function _getVirtualSupply(uint256 bptBalance) internal view returns (uint256) { return totalSupply().sub(bptBalance); } /** * @dev Computes an approximation of virtual supply, which costs less gas than `_getVirtualSupply` and returns the * same value in all cases except when the emergency pause has been enabled and BPT burned as part of the emergency * exit process. */ function _getApproximateVirtualSupply(uint256 bptBalance) internal pure returns (uint256) { // No need for checked arithmetic as _INITIAL_BPT_SUPPLY is always greater than any valid Vault BPT balance. return _INITIAL_BPT_SUPPLY - bptBalance; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; uint256 internal constant NOT_TWO_TOKENS = 210; uint256 internal constant DISABLED = 211; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312; uint256 internal constant ORACLE_NOT_INITIALIZED = 313; uint256 internal constant ORACLE_QUERY_TOO_OLD = 314; uint256 internal constant ORACLE_INVALID_INDEX = 315; uint256 internal constant ORACLE_BAD_SECS = 316; uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317; uint256 internal constant AMP_ONGOING_UPDATE = 318; uint256 internal constant AMP_RATE_TOO_HIGH = 319; uint256 internal constant AMP_NO_ONGOING_UPDATE = 320; uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321; uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322; uint256 internal constant RELAYER_NOT_CONTRACT = 323; uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324; uint256 internal constant REBALANCING_RELAYER_REENTERED = 325; uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326; uint256 internal constant SWAPS_DISABLED = 327; uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328; uint256 internal constant PRICE_RATE_OVERFLOW = 329; uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330; uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331; uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332; uint256 internal constant UPPER_TARGET_TOO_HIGH = 333; uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334; uint256 internal constant OUT_OF_TARGET_RANGE = 335; uint256 internal constant UNHANDLED_EXIT_KIND = 336; uint256 internal constant UNAUTHORIZED_EXIT = 337; uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338; uint256 internal constant UNHANDLED_BY_MANAGED_POOL = 339; uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340; uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341; uint256 internal constant INVALID_INITIALIZATION = 342; uint256 internal constant OUT_OF_NEW_TARGET_RANGE = 343; uint256 internal constant UNAUTHORIZED_OPERATION = 344; uint256 internal constant UNINITIALIZED_POOL_CONTROLLER = 345; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; uint256 internal constant CALLER_IS_NOT_OWNER = 426; uint256 internal constant NEW_OWNER_IS_ZERO = 427; uint256 internal constant CODE_DEPLOYMENT_FAILED = 428; uint256 internal constant CALL_TO_NON_CONTRACT = 429; uint256 internal constant LOW_LEVEL_CALL_FAILED = 430; uint256 internal constant NOT_PAUSED = 431; uint256 internal constant ADDRESS_ALREADY_ALLOWLISTED = 432; uint256 internal constant ADDRESS_NOT_ALLOWLISTED = 433; uint256 internal constant ERC20_BURN_EXCEEDS_BALANCE = 434; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-vault/contracts/interfaces/IAsset.sol"; import "../openzeppelin/IERC20.sol"; // solhint-disable function _asIAsset(IERC20[] memory tokens) pure returns (IAsset[] memory assets) { // solhint-disable-next-line no-inline-assembly assembly { assets := tokens } } function _sortTokens( IERC20 tokenA, IERC20 tokenB, IERC20 tokenC ) pure returns (IERC20[] memory tokens) { (uint256 indexTokenA, uint256 indexTokenB, uint256 indexTokenC) = _getSortedTokenIndexes(tokenA, tokenB, tokenC); tokens = new IERC20[](3); tokens[indexTokenA] = tokenA; tokens[indexTokenB] = tokenB; tokens[indexTokenC] = tokenC; } function _insertSorted(IERC20[] memory tokens, IERC20 token) pure returns (IERC20[] memory sorted) { sorted = new IERC20[](tokens.length + 1); if (tokens.length == 0) { sorted[0] = token; return sorted; } uint256 i; for (i = tokens.length; i > 0 && tokens[i - 1] > token; i--) sorted[i] = tokens[i - 1]; for (uint256 j = 0; j < i; j++) sorted[j] = tokens[j]; sorted[i] = token; } function _getSortedTokenIndexes( IERC20 tokenA, IERC20 tokenB, IERC20 tokenC ) pure returns ( uint256 indexTokenA, uint256 indexTokenB, uint256 indexTokenC ) { if (tokenA < tokenB) { if (tokenB < tokenC) { // (tokenA, tokenB, tokenC) return (0, 1, 2); } else if (tokenA < tokenC) { // (tokenA, tokenC, tokenB) return (0, 2, 1); } else { // (tokenC, tokenA, tokenB) return (1, 2, 0); } } else { // tokenB < tokenA if (tokenC < tokenB) { // (tokenC, tokenB, tokenA) return (2, 1, 0); } else if (tokenC < tokenA) { // (tokenB, tokenC, tokenA) return (2, 0, 1); } else { // (tokenB, tokenA, tokenC) return (1, 0, 2); } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./LogExpMath.sol"; import "../helpers/BalancerErrors.sol"; /* solhint-disable private-vars-leading-underscore */ library FixedPoint { uint256 internal constant ONE = 1e18; // 18 decimal places uint256 internal constant TWO = 2 * ONE; uint256 internal constant FOUR = 4 * ONE; uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14) // Minimum base for the power function when the exponent is 'free' (larger than ONE). uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18; function add(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); return product / ONE; } function mulUp(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); if (product == 0) { return 0; } else { // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((product - 1) / ONE) + 1; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow return aInflated / b; } } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((aInflated - 1) / b) + 1; } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above * the true value (that is, the error function expected - actual is always positive). */ function powDown(uint256 x, uint256 y) internal pure returns (uint256) { // Optimize for when y equals 1.0, 2.0 or 4.0, as those are very simple to implement and occur often in 50/50 // and 80/20 Weighted Pools if (y == ONE) { return x; } else if (y == TWO) { return mulDown(x, x); } else if (y == FOUR) { uint256 square = mulDown(x, x); return mulDown(square, square); } else { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); if (raw < maxError) { return 0; } else { return sub(raw, maxError); } } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below * the true value (that is, the error function expected - actual is always negative). */ function powUp(uint256 x, uint256 y) internal pure returns (uint256) { // Optimize for when y equals 1.0, 2.0 or 4.0, as those are very simple to implement and occur often in 50/50 // and 80/20 Weighted Pools if (y == ONE) { return x; } else if (y == TWO) { return mulUp(x, x); } else if (y == FOUR) { uint256 square = mulUp(x, x); return mulUp(square, square); } else { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); return add(raw, maxError); } } /** * @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1. * * Useful when computing the complement for values with some level of relative error, as it strips this error and * prevents intermediate negative values. */ function complement(uint256 x) internal pure returns (uint256) { return (x < ONE) ? (ONE - x) : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/TemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IBasePool.sol"; import "@balancer-labs/v2-asset-manager-utils/contracts/IAssetManager.sol"; import "./BalancerPoolToken.sol"; import "./BasePoolAuthorization.sol"; // solhint-disable max-states-count /** * @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with optional * Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism. * * Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that * derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the * `whenNotPaused` modifier. * * No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer. * * Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from * BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces * and implement the swap callbacks themselves. */ abstract contract LegacyBasePool is IBasePool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable { using WordCodec for bytes32; using FixedPoint for uint256; uint256 private constant _MIN_TOKENS = 2; uint256 private constant _DEFAULT_MINIMUM_BPT = 1e6; // 1e18 corresponds to 1.0, or a 100% fee uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% - this fits in 64 bits // Storage slot that can be used to store unrelated pieces of information. In particular, by default is used // to store only the swap fee percentage of a pool. But it can be extended to store some more pieces of information. // The swap fee percentage is stored in the most-significant 64 bits, therefore the remaining 192 bits can be // used to store any other piece of information. bytes32 private _miscData; uint256 private constant _SWAP_FEE_PERCENTAGE_OFFSET = 192; bytes32 private immutable _poolId; event SwapFeePercentageChanged(uint256 swapFeePercentage); constructor( IVault vault, IVault.PoolSpecialization specialization, string memory name, string memory symbol, IERC20[] memory tokens, address[] memory assetManagers, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) // Base Pools are expected to be deployed using factories. By using the factory address as the action // disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for // simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in // any Pool created by the same factory), while still making action identifiers unique among different factories // if the selectors match, preventing accidental errors. Authentication(bytes32(uint256(msg.sender))) BalancerPoolToken(name, symbol, vault) BasePoolAuthorization(owner) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) { _require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS); _require(tokens.length <= _getMaxTokens(), Errors.MAX_TOKENS); // The Vault only requires the token list to be ordered for the Two Token Pools specialization. However, // to make the developer experience consistent, we are requiring this condition for all the native pools. // Also, since these Pools will register tokens only once, we can ensure the Pool tokens will follow the same // order. We rely on this property to make Pools simpler to write, as it lets us assume that the // order of token-specific parameters (such as token weights) will not change. InputHelpers.ensureArrayIsSorted(tokens); _setSwapFeePercentage(swapFeePercentage); bytes32 poolId = vault.registerPool(specialization); vault.registerTokens(poolId, tokens, assetManagers); // Set immutable state variables - these cannot be read from during construction _poolId = poolId; } // Getters / Setters function getPoolId() public view override returns (bytes32) { return _poolId; } function _getTotalTokens() internal view virtual returns (uint256); function _getMaxTokens() internal pure virtual returns (uint256); /** * @dev Returns the minimum BPT supply. This amount is minted to the zero address during initialization, effectively * locking it. * * This is useful to make sure Pool initialization happens only once, but derived Pools can change this value (even * to zero) by overriding this function. */ function _getMinimumBpt() internal pure virtual returns (uint256) { return _DEFAULT_MINIMUM_BPT; } function getSwapFeePercentage() public view returns (uint256) { return _miscData.decodeUint64(_SWAP_FEE_PERCENTAGE_OFFSET); } function setSwapFeePercentage(uint256 swapFeePercentage) public virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _miscData = _miscData.insertUint64(swapFeePercentage, _SWAP_FEE_PERCENTAGE_OFFSET); emit SwapFeePercentageChanged(swapFeePercentage); } function setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) public virtual authenticate whenNotPaused { _setAssetManagerPoolConfig(token, poolConfig); } function _setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) private { bytes32 poolId = getPoolId(); (, , , address assetManager) = getVault().getPoolTokenInfo(poolId, token); IAssetManager(assetManager).setConfig(poolId, poolConfig); } function setPaused(bool paused) external authenticate { _setPaused(paused); } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return (actionId == getActionId(this.setSwapFeePercentage.selector)) || (actionId == getActionId(this.setAssetManagerPoolConfig.selector)); } function _getMiscData() internal view returns (bytes32) { return _miscData; } /** * Inserts data into the least-significant 192 bits of the misc data storage slot. * Note that the remaining 64 bits are used for the swap fee percentage and cannot be overloaded. */ function _setMiscData(bytes32 newData) internal { _miscData = _miscData.insertBits192(newData, 0); } // Join / Exit Hooks modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); if (totalSupply() == 0) { (uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool( poolId, sender, recipient, scalingFactors, userData ); // On initialization, we lock _getMinimumBpt() by minting it for the zero address. This BPT acts as a // minimum as it will never be burned, which reduces potential issues with rounding, and also prevents the // Pool from ever being fully drained. _require(bptAmountOut >= _getMinimumBpt(), Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _getMinimumBpt()); _mintPoolTokens(recipient, bptAmountOut - _getMinimumBpt()); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); return (amountsIn, new uint256[](_getTotalTokens())); } else { _upscaleArray(balances, scalingFactors); (uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); // Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it. _mintPoolTokens(recipient, bptAmountOut); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); // dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsIn, dueProtocolFeeAmounts); } } function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); // Note we no longer use `balances` after calling `_onExitPool`, which may mutate it. _burnPoolTokens(sender, bptAmountIn); // Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(amountsOut, scalingFactors); _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsOut, dueProtocolFeeAmounts); } // Query functions /** * @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the * Vault with the same arguments, along with the number of tokens `sender` would have to supply. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptOut, amountsIn); } /** * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the * Vault with the same arguments, along with the number of tokens `recipient` would receive. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptIn, amountsOut); } // Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are // upscaled. /** * @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero. * * Returns the amount of BPT to mint, and the token amounts the Pool will receive in return. * * Minted BPT will be sent to `recipient`, except for _getMinimumBpt(), which will be deducted from this amount and * sent to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP * from ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire * Pool's lifetime. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. */ function _onInitializePool( bytes32 poolId, address sender, address recipient, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn); /** * @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`). * * Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of * tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * Minted BPT will be sent to `recipient`. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns ( uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ); /** * @dev Called whenever the Pool is exited. * * Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and * the number of tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * BPT will be burnt from `sender`. * * The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled * (rounding down) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ); // Internal functions /** * @dev Adds swap fee amount to `amount`, returning a higher value. */ function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount + fee amount, so we round up (favoring a higher fee amount). return amount.divUp(FixedPoint.ONE.sub(getSwapFeePercentage())); } /** * @dev Subtracts swap fee amount from `amount`, returning a lower value. */ function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount - fee amount, so we round up (favoring a higher fee amount). uint256 feeAmount = amount.mulUp(getSwapFeePercentage()); return amount.sub(feeAmount); } // Scaling /** * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if * it had 18 decimals. */ function _computeScalingFactor(IERC20 token) internal view returns (uint256) { if (address(token) == address(this)) { return FixedPoint.ONE; } // Tokens that don't implement the `decimals` method are not supported. uint256 tokenDecimals = ERC20(address(token)).decimals(); // Tokens with more than 18 decimals are not supported. uint256 decimalsDifference = Math.sub(18, tokenDecimals); return FixedPoint.ONE * 10**decimalsDifference; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. * * All scaling factors are fixed-point values with 18 decimals, to allow for this function to be overridden by * derived contracts that need to apply further scaling, making these factors potentially non-integer. * * The largest 'base' scaling factor (i.e. in tokens with less than 18 decimals) is 10**18, which in fixed-point is * 10**36. This value can be multiplied with a 112 bit Vault balance with no overflow by a factor of ~1e7, making * even relatively 'large' factors safe to use. * * The 1e7 figure is the result of 2**256 / (1e18 * 1e18 * 2**112). */ function _scalingFactor(IERC20 token) internal view virtual returns (uint256); /** * @dev Same as `_scalingFactor()`, except for all registered tokens (in the same order as registered). The Vault * will always pass balances in this order when calling any of the Pool hooks. */ function _scalingFactors() internal view virtual returns (uint256[] memory); function getScalingFactors() external view returns (uint256[] memory) { return _scalingFactors(); } /** * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed * scaling or not. */ function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { // Upscale rounding wouldn't necessarily always go in the same direction: in a swap for example the balance of // token in should be rounded up, and that of token out rounded down. This is the only place where we round in // the same direction for all amounts, as the impact of this rounding is expected to be minimal (and there's no // rounding error unless `_scalingFactor()` is overriden). return FixedPoint.mulDown(amount, scalingFactor); } /** * @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates* * the `amounts` array. */ function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.mulDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded down. */ function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return FixedPoint.divDown(amount, scalingFactor); } /** * @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleDownArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.divDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded up. */ function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return FixedPoint.divUp(amount, scalingFactor); } /** * @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.divUp(amounts[i], scalingFactors[i]); } } function _getAuthorizer() internal view override returns (IAuthorizer) { // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which // accounts can call permissioned functions: for example, to perform emergency pauses. // If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under // Governance control. return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory, uint256[] memory) internal view _downscaleArray ) private { // This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed // explanation. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the bpt and token amounts from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of the // `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded // representation of these. // An ABI-encoded response will include one additional field to indicate the starting offset of // the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the // returndata. // // In returndata: // [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ] // [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // // We now need to return (ABI-encoded values): // [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ] // [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // We copy 32 bytes for the `bptAmount` from returndata into memory. // Note that we skip the first 4 bytes for the error signature returndatacopy(0, 0x04, 32) // The offsets are 32-bytes long, so the array of `tokenAmounts` will start after // the initial 64 bytes. mstore(0x20, 64) // We now copy the raw memory array for the `tokenAmounts` from returndata into memory. // Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also // skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount. returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) // We finally return the ABI-encoded uint256 and the array, which has a total length equal to // the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the // error signature. return(0, add(returndatasize(), 28)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); _downscaleArray(tokenAmounts, scalingFactors); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of // a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values // Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32 let size := mul(mload(tokenAmounts), 32) // We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there // will be at least one available slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) // We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb // We use the previous slot to `bptAmount`. mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) // When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return // the `bptAmount`, the array 's length, and the error signature. revert(start, add(size, 68)) } } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IRateProvider { /** * @dev Returns an 18 decimal fixed point number that is the exchange rate of the token to some other underlying * token. The meaning of this rate depends on the context. */ function getRate() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/BalancerErrors.sol"; /** * Price rate caches are used to avoid querying the price rate for a token every time we need to work with it. It is * useful for slow changing rates, such as those that arise from interest-bearing tokens (e.g. waDAI into DAI). * * The cache data is packed into a single bytes32 value with the following structure: * [ expires | duration | price rate value ] * [ uint64 | uint64 | uint128 ] * [ MSB LSB ] * * * 'rate' is an 18 decimal fixed point number, supporting rates of up to ~3e20. 'expires' is a Unix timestamp, and * 'duration' is expressed in seconds. */ library PriceRateCache { using WordCodec for bytes32; uint256 private constant _PRICE_RATE_CACHE_VALUE_OFFSET = 0; uint256 private constant _PRICE_RATE_CACHE_DURATION_OFFSET = 128; uint256 private constant _PRICE_RATE_CACHE_EXPIRES_OFFSET = 128 + 64; /** * @dev Returns the rate of a price rate cache. */ function getRate(bytes32 cache) internal pure returns (uint256) { return cache.decodeUint128(_PRICE_RATE_CACHE_VALUE_OFFSET); } /** * @dev Returns the duration of a price rate cache. */ function getDuration(bytes32 cache) internal pure returns (uint256) { return cache.decodeUint64(_PRICE_RATE_CACHE_DURATION_OFFSET); } /** * @dev Returns the duration and expiration time of a price rate cache. */ function getTimestamps(bytes32 cache) internal pure returns (uint256 duration, uint256 expires) { duration = getDuration(cache); expires = cache.decodeUint64(_PRICE_RATE_CACHE_EXPIRES_OFFSET); } /** * @dev Encodes rate and duration into a price rate cache. The expiration time is computed automatically, counting * from the current time. */ function encode(uint256 rate, uint256 duration) internal view returns (bytes32) { _require(rate < 2**128, Errors.PRICE_RATE_OVERFLOW); // solhint-disable not-rely-on-time return WordCodec.encodeUint(uint128(rate), _PRICE_RATE_CACHE_VALUE_OFFSET) | WordCodec.encodeUint(uint64(duration), _PRICE_RATE_CACHE_DURATION_OFFSET) | WordCodec.encodeUint(uint64(block.timestamp + duration), _PRICE_RATE_CACHE_EXPIRES_OFFSET); } /** * @dev Returns rate, duration and expiration time of a price rate cache. */ function decode(bytes32 cache) internal pure returns ( uint256 rate, uint256 duration, uint256 expires ) { rate = getRate(cache); (duration, expires) = getTimestamps(cache); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev IPools with the General specialization setting should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will * grant to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IGeneralPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) external returns (uint256 amount); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; // These functions start with an underscore, as if they were part of a contract and not a library. At some point this // should be fixed. // solhint-disable private-vars-leading-underscore library LinearMath { using FixedPoint for uint256; // A thorough derivation of the formulas and derivations found here exceeds the scope of this file, so only // introductory notions will be presented. // A Linear Pool holds three tokens: the main token, the wrapped token, and the Pool share token (BPT). It is // possible to exchange any of these tokens for any of the other two (so we have three trading pairs) in both // directions (the first token of each pair can be bought or sold for the second) and by specifying either the input // or output amount (typically referred to as 'given in' or 'given out'). A full description thus requires // 3*2*2 = 12 functions. // Wrapped tokens have a known, trusted exchange rate to main tokens. All functions here assume such a rate has // already been applied, meaning main and wrapped balances can be compared as they are both expressed in the same // units (those of main token). // Additionally, Linear Pools feature a lower and upper target that represent the desired range of values for the // main token balance. Any action that moves the main balance away from this range is charged a proportional fee, // and any action that moves it towards this range is incentivized by paying the actor using these collected fees. // The collected fees are not stored in a separate data structure: they are a function of the current main balance, // targets and fee percentage. The main balance sans fees is known as the 'nominal balance', which is always smaller // than the real balance except when the real balance is within the targets. // The rule under which Linear Pools conduct trades between main and wrapped tokens is by keeping the sum of nominal // main balance and wrapped balance constant: this value is known as the 'invariant'. BPT is backed by nominal // reserves, meaning its supply is proportional to the invariant. As the wrapped token appreciates in value and its // exchange rate to the main token increases, so does the invariant and thus the value of BPT (in main token units). struct Params { uint256 fee; uint256 lowerTarget; uint256 upperTarget; } function _calcBptOutPerMainIn( uint256 mainIn, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount out, so we round down overall. if (bptSupply == 0) { // BPT typically grows in the same ratio the invariant does. The first time liquidity is added however, the // BPT supply is initialized to equal the invariant (which in this case is just the nominal main balance as // there is no wrapped balance). return _toNominal(mainIn, params); } uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 afterNominalMain = _toNominal(mainBalance.add(mainIn), params); uint256 deltaNominalMain = afterNominalMain.sub(previousNominalMain); uint256 invariant = _calcInvariant(previousNominalMain, wrappedBalance); return Math.divDown(Math.mul(bptSupply, deltaNominalMain), invariant); } function _calcBptInPerMainOut( uint256 mainOut, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount in, so we round up overall. uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 afterNominalMain = _toNominal(mainBalance.sub(mainOut), params); uint256 deltaNominalMain = previousNominalMain.sub(afterNominalMain); uint256 invariant = _calcInvariant(previousNominalMain, wrappedBalance); return Math.divUp(Math.mul(bptSupply, deltaNominalMain), invariant); } function _calcWrappedOutPerMainIn( uint256 mainIn, uint256 mainBalance, Params memory params ) internal pure returns (uint256) { // Amount out, so we round down overall. uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 afterNominalMain = _toNominal(mainBalance.add(mainIn), params); return afterNominalMain.sub(previousNominalMain); } function _calcWrappedInPerMainOut( uint256 mainOut, uint256 mainBalance, Params memory params ) internal pure returns (uint256) { // Amount in, so we round up overall. uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 afterNominalMain = _toNominal(mainBalance.sub(mainOut), params); return previousNominalMain.sub(afterNominalMain); } function _calcMainInPerBptOut( uint256 bptOut, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount in, so we round up overall. if (bptSupply == 0) { // BPT typically grows in the same ratio the invariant does. The first time liquidity is added however, the // BPT supply is initialized to equal the invariant (which in this case is just the nominal main balance as // there is no wrapped balance). return _fromNominal(bptOut, params); } uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 invariant = _calcInvariant(previousNominalMain, wrappedBalance); uint256 deltaNominalMain = Math.divUp(Math.mul(invariant, bptOut), bptSupply); uint256 afterNominalMain = previousNominalMain.add(deltaNominalMain); uint256 newMainBalance = _fromNominal(afterNominalMain, params); return newMainBalance.sub(mainBalance); } function _calcMainOutPerBptIn( uint256 bptIn, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount out, so we round down overall. uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 invariant = _calcInvariant(previousNominalMain, wrappedBalance); uint256 deltaNominalMain = Math.divDown(Math.mul(invariant, bptIn), bptSupply); uint256 afterNominalMain = previousNominalMain.sub(deltaNominalMain); uint256 newMainBalance = _fromNominal(afterNominalMain, params); return mainBalance.sub(newMainBalance); } function _calcMainOutPerWrappedIn( uint256 wrappedIn, uint256 mainBalance, Params memory params ) internal pure returns (uint256) { // Amount out, so we round down overall. uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 afterNominalMain = previousNominalMain.sub(wrappedIn); uint256 newMainBalance = _fromNominal(afterNominalMain, params); return mainBalance.sub(newMainBalance); } function _calcMainInPerWrappedOut( uint256 wrappedOut, uint256 mainBalance, Params memory params ) internal pure returns (uint256) { // Amount in, so we round up overall. uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 afterNominalMain = previousNominalMain.add(wrappedOut); uint256 newMainBalance = _fromNominal(afterNominalMain, params); return newMainBalance.sub(mainBalance); } function _calcBptOutPerWrappedIn( uint256 wrappedIn, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount out, so we round down overall. if (bptSupply == 0) { // BPT typically grows in the same ratio the invariant does. The first time liquidity is added however, the // BPT supply is initialized to equal the invariant (which in this case is just the wrapped balance as // there is no main balance). return wrappedIn; } uint256 nominalMain = _toNominal(mainBalance, params); uint256 previousInvariant = _calcInvariant(nominalMain, wrappedBalance); uint256 newWrappedBalance = wrappedBalance.add(wrappedIn); uint256 newInvariant = _calcInvariant(nominalMain, newWrappedBalance); uint256 newBptBalance = Math.divDown(Math.mul(bptSupply, newInvariant), previousInvariant); return newBptBalance.sub(bptSupply); } function _calcBptInPerWrappedOut( uint256 wrappedOut, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount in, so we round up overall. uint256 nominalMain = _toNominal(mainBalance, params); uint256 previousInvariant = _calcInvariant(nominalMain, wrappedBalance); uint256 newWrappedBalance = wrappedBalance.sub(wrappedOut); uint256 newInvariant = _calcInvariant(nominalMain, newWrappedBalance); uint256 newBptBalance = Math.divDown(Math.mul(bptSupply, newInvariant), previousInvariant); return bptSupply.sub(newBptBalance); } function _calcWrappedInPerBptOut( uint256 bptOut, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount in, so we round up overall. if (bptSupply == 0) { // BPT typically grows in the same ratio the invariant does. The first time liquidity is added however, the // BPT supply is initialized to equal the invariant (which in this case is just the wrapped balance as // there is no main balance). return bptOut; } uint256 nominalMain = _toNominal(mainBalance, params); uint256 previousInvariant = _calcInvariant(nominalMain, wrappedBalance); uint256 newBptBalance = bptSupply.add(bptOut); uint256 newWrappedBalance = Math.divUp(Math.mul(newBptBalance, previousInvariant), bptSupply).sub(nominalMain); return newWrappedBalance.sub(wrappedBalance); } function _calcWrappedOutPerBptIn( uint256 bptIn, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount out, so we round down overall. uint256 nominalMain = _toNominal(mainBalance, params); uint256 previousInvariant = _calcInvariant(nominalMain, wrappedBalance); uint256 newBptBalance = bptSupply.sub(bptIn); uint256 newWrappedBalance = Math.divUp(Math.mul(newBptBalance, previousInvariant), bptSupply).sub(nominalMain); return wrappedBalance.sub(newWrappedBalance); } function _calcInvariant(uint256 nominalMainBalance, uint256 wrappedBalance) internal pure returns (uint256) { return nominalMainBalance.add(wrappedBalance); } function _toNominal(uint256 real, Params memory params) internal pure returns (uint256) { // Fees are always rounded down: either direction would work but we need to be consistent, and rounding down // uses less gas. if (real < params.lowerTarget) { uint256 fees = (params.lowerTarget - real).mulDown(params.fee); return real.sub(fees); } else if (real <= params.upperTarget) { return real; } else { uint256 fees = (real - params.upperTarget).mulDown(params.fee); return real.sub(fees); } } function _fromNominal(uint256 nominal, Params memory params) internal pure returns (uint256) { // Since real = nominal + fees, rounding down fees is equivalent to rounding down real. if (nominal < params.lowerTarget) { return (nominal.add(params.fee.mulDown(params.lowerTarget))).divDown(FixedPoint.ONE.add(params.fee)); } else if (nominal <= params.upperTarget) { return nominal; } else { return (nominal.sub(params.fee.mulDown(params.upperTarget)).divDown(FixedPoint.ONE.sub(params.fee))); } } function _calcTokensOutGivenExactBptIn( uint256[] memory balances, uint256 bptAmountIn, uint256 bptTotalSupply, uint256 bptIndex ) internal pure returns (uint256[] memory) { /********************************************************************************************** // exactBPTInForTokensOut // // (per token) // // aO = tokenAmountOut / bptIn \ // // b = tokenBalance a0 = b * | --------------------- | // // bptIn = bptAmountIn \ bptTotalSupply / // // bpt = bptTotalSupply // **********************************************************************************************/ // Since we're computing an amount out, we round down overall. This means rounding down on both the // multiplication and division. uint256 bptRatio = bptAmountIn.divDown(bptTotalSupply); uint256[] memory amountsOut = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { // BPT is skipped as those tokens are not the LPs, but rather the preminted and undistributed amount. if (i != bptIndex) { amountsOut[i] = balances[i].mulDown(bptRatio); } } return amountsOut; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./LinearPool.sol"; library LinearPoolUserData { enum ExitKind { EMERGENCY_EXACT_BPT_IN_FOR_TOKENS_OUT } function exitKind(bytes memory self) internal pure returns (ExitKind) { return abi.decode(self, (ExitKind)); } function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) { (, bptAmountIn) = abi.decode(self, (ExitKind, uint256)); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the “Software”), to deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the // Software. // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /* solhint-disable */ /** * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). * * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural * exponentiation and logarithm (where the base is Euler's number). * * @author Fernando Martinelli - @fernandomartinelli * @author Sergio Yuhjtman - @sergioyuhjtman * @author Daniel Fernandez - @dmf7z */ library LogExpMath { // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying // two numbers, and multiply by ONE when dividing them. // All arguments and return values are 18 decimal fixed point numbers. int256 constant ONE_18 = 1e18; // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the // case of ln36, 36 decimals. int256 constant ONE_20 = 1e20; int256 constant ONE_36 = 1e36; // The domain of natural exponentiation is bound by the word size and number of decimals used. // // Because internally the result will be stored using 20 decimals, the largest possible result is // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. // The smallest possible result is 10^(-18), which makes largest negative argument // ln(10^(-18)) = -41.446531673892822312. // We use 130.0 and -41.0 to have some safety margin. int256 constant MAX_NATURAL_EXPONENT = 130e18; int256 constant MIN_NATURAL_EXPONENT = -41e18; // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point // 256 bit integer. int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20); // 18 decimal constants int256 constant x0 = 128000000000000000000; // 2ˆ7 int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) int256 constant x1 = 64000000000000000000; // 2ˆ6 int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) // 20 decimal constants int256 constant x2 = 3200000000000000000000; // 2ˆ5 int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) int256 constant x3 = 1600000000000000000000; // 2ˆ4 int256 constant a3 = 888611052050787263676000000; // eˆ(x3) int256 constant x4 = 800000000000000000000; // 2ˆ3 int256 constant a4 = 298095798704172827474000; // eˆ(x4) int256 constant x5 = 400000000000000000000; // 2ˆ2 int256 constant a5 = 5459815003314423907810; // eˆ(x5) int256 constant x6 = 200000000000000000000; // 2ˆ1 int256 constant a6 = 738905609893065022723; // eˆ(x6) int256 constant x7 = 100000000000000000000; // 2ˆ0 int256 constant a7 = 271828182845904523536; // eˆ(x7) int256 constant x8 = 50000000000000000000; // 2ˆ-1 int256 constant a8 = 164872127070012814685; // eˆ(x8) int256 constant x9 = 25000000000000000000; // 2ˆ-2 int256 constant a9 = 128402541668774148407; // eˆ(x9) int256 constant x10 = 12500000000000000000; // 2ˆ-3 int256 constant a10 = 113314845306682631683; // eˆ(x10) int256 constant x11 = 6250000000000000000; // 2ˆ-4 int256 constant a11 = 106449445891785942956; // eˆ(x11) /** * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. * * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. */ function pow(uint256 x, uint256 y) internal pure returns (uint256) { if (y == 0) { // We solve the 0^0 indetermination by making it equal one. return uint256(ONE_18); } if (x == 0) { return 0; } // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means // x^y = exp(y * ln(x)). // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. _require(x < 2**255, Errors.X_OUT_OF_BOUNDS); int256 x_int256 = int256(x); // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. _require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS); int256 y_int256 = int256(y); int256 logx_times_y; if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { int256 ln_36_x = _ln_36(x_int256); // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the // (downscaled) last 18 decimals. logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); } else { logx_times_y = _ln(x_int256) * y_int256; } logx_times_y /= ONE_18; // Finally, we compute exp(y * ln(x)) to arrive at x^y _require( MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, Errors.PRODUCT_OUT_OF_BOUNDS ); return uint256(exp(logx_times_y)); } /** * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. * * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. */ function exp(int256 x) internal pure returns (int256) { _require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT); if (x < 0) { // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). // Fixed point division requires multiplying by ONE_18. return ((ONE_18 * ONE_18) / exp(-x)); } // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the // decomposition. // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this // decomposition, which will be lower than the smallest x_n. // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. // We mutate x by subtracting x_n, making it the remainder of the decomposition. // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause // intermediate overflows. Instead we store them as plain integers, with 0 decimals. // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the // decomposition. // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct // it and compute the accumulated product. int256 firstAN; if (x >= x0) { x -= x0; firstAN = a0; } else if (x >= x1) { x -= x1; firstAN = a1; } else { firstAN = 1; // One with no decimal places } // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the // smaller terms. x *= 100; // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point // one. Recall that fixed point multiplication requires dividing by ONE_20. int256 product = ONE_20; if (x >= x2) { x -= x2; product = (product * a2) / ONE_20; } if (x >= x3) { x -= x3; product = (product * a3) / ONE_20; } if (x >= x4) { x -= x4; product = (product * a4) / ONE_20; } if (x >= x5) { x -= x5; product = (product * a5) / ONE_20; } if (x >= x6) { x -= x6; product = (product * a6) / ONE_20; } if (x >= x7) { x -= x7; product = (product * a7) / ONE_20; } if (x >= x8) { x -= x8; product = (product * a8) / ONE_20; } if (x >= x9) { x -= x9; product = (product * a9) / ONE_20; } // x10 and x11 are unnecessary here since we have high enough precision already. // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. int256 term; // Each term in the sum, where the nth term is (x^n / n!). // The first term is simply x. term = x; seriesSum += term; // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. term = ((term * x) / ONE_20) / 2; seriesSum += term; term = ((term * x) / ONE_20) / 3; seriesSum += term; term = ((term * x) / ONE_20) / 4; seriesSum += term; term = ((term * x) / ONE_20) / 5; seriesSum += term; term = ((term * x) / ONE_20) / 6; seriesSum += term; term = ((term * x) / ONE_20) / 7; seriesSum += term; term = ((term * x) / ONE_20) / 8; seriesSum += term; term = ((term * x) / ONE_20) / 9; seriesSum += term; term = ((term * x) / ONE_20) / 10; seriesSum += term; term = ((term * x) / ONE_20) / 11; seriesSum += term; term = ((term * x) / ONE_20) / 12; seriesSum += term; // 12 Taylor terms are sufficient for 18 decimal precision. // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), // and then drop two digits to return an 18 decimal value. return (((product * seriesSum) / ONE_20) * firstAN) / 100; } /** * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument. */ function log(int256 arg, int256 base) internal pure returns (int256) { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = _ln_36(base); } else { logBase = _ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = _ln_36(arg); } else { logArg = _ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; } /** * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function ln(int256 a) internal pure returns (int256) { // The real natural logarithm is not defined for negative numbers or zero. _require(a > 0, Errors.OUT_OF_BOUNDS); if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) { return _ln_36(a) / ONE_18; } else { return _ln(a); } } /** * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function _ln(int256 a) private pure returns (int256) { if (a < ONE_18) { // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. // Fixed point division requires multiplying by ONE_18. return (-_ln((ONE_18 * ONE_18) / a)); } // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this // decomposition, which will be lower than the smallest a_n. // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. // We mutate a by subtracting a_n, making it the remainder of the decomposition. // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by // ONE_18 to convert them to fixed point. // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide // by it and compute the accumulated sum. int256 sum = 0; if (a >= a0 * ONE_18) { a /= a0; // Integer, not fixed point division sum += x0; } if (a >= a1 * ONE_18) { a /= a1; // Integer, not fixed point division sum += x1; } // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. sum *= 100; a *= 100; // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. if (a >= a2) { a = (a * ONE_20) / a2; sum += x2; } if (a >= a3) { a = (a * ONE_20) / a3; sum += x3; } if (a >= a4) { a = (a * ONE_20) / a4; sum += x4; } if (a >= a5) { a = (a * ONE_20) / a5; sum += x5; } if (a >= a6) { a = (a * ONE_20) / a6; sum += x6; } if (a >= a7) { a = (a * ONE_20) / a7; sum += x7; } if (a >= a8) { a = (a * ONE_20) / a8; sum += x8; } if (a >= a9) { a = (a * ONE_20) / a9; sum += x9; } if (a >= a10) { a = (a * ONE_20) / a10; sum += x10; } if (a >= a11) { a = (a * ONE_20) / a11; sum += x11; } // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series // that converges rapidly for values of `a` close to one - the same one used in ln_36. // Let z = (a - 1) / (a + 1). // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires // division by ONE_20. int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_20; seriesSum += num / 3; num = (num * z_squared) / ONE_20; seriesSum += num / 5; num = (num * z_squared) / ONE_20; seriesSum += num / 7; num = (num * z_squared) / ONE_20; seriesSum += num / 9; num = (num * z_squared) / ONE_20; seriesSum += num / 11; // 6 Taylor terms are sufficient for 36 decimal precision. // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) seriesSum *= 2; // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal // value. return (sum + seriesSum) / 100; } /** * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function _ln_36(int256 x) private pure returns (int256) { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. * Adapted from OpenZeppelin's SafeMath library. */ library Math { /** * @dev Returns the absolute value of a signed integer. */ function abs(int256 a) internal pure returns (uint256) { return a > 0 ? uint256(a) : uint256(-a); } /** * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the addition of two signed integers, reverting on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; _require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW); return c; } /** * @dev Returns the largest of two numbers of 256 bits. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers of 256 bits. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW); return c; } function div( uint256 a, uint256 b, bool roundUp ) internal pure returns (uint256) { return roundUp ? divUp(a, b) : divDown(a, b); } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); return a / b; } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { return 1 + (a - 1) / b; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; import "./BalancerErrors.sol"; library InputHelpers { function ensureInputLengthMatch(uint256 a, uint256 b) internal pure { _require(a == b, Errors.INPUT_LENGTH_MISMATCH); } function ensureInputLengthMatch( uint256 a, uint256 b, uint256 c ) internal pure { _require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH); } function ensureArrayIsSorted(IERC20[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(address[] memory array) internal pure { if (array.length < 2) { return; } address previous = array[0]; for (uint256 i = 1; i < array.length; ++i) { address current = array[i]; _require(previous < current, Errors.UNSORTED_ARRAY); previous = current; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./ITemporarilyPausable.sol"; /** * @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be * used as an emergency switch in case a security vulnerability or threat is identified. * * The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be * unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets * system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful * analysis later determines there was a false alarm. * * If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional * Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time * to react to an emergency, even if the threat is discovered shortly before the Pause Window expires. * * Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is * irreversible. */ abstract contract TemporarilyPausable is ITemporarilyPausable { // The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy. // solhint-disable not-rely-on-time uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days; uint256 private immutable _pauseWindowEndTime; uint256 private immutable _bufferPeriodEndTime; bool private _paused; constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { _require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION); _require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION); uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration; _pauseWindowEndTime = pauseWindowEndTime; _bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration; } /** * @dev Reverts if the contract is paused. */ modifier whenNotPaused() { _ensureNotPaused(); _; } /** * @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer * Period. */ function getPausedState() external view override returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ) { paused = !_isNotPaused(); pauseWindowEndTime = _getPauseWindowEndTime(); bufferPeriodEndTime = _getBufferPeriodEndTime(); } /** * @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and * unpaused until the end of the Buffer Period. * * Once the Buffer Period expires, this function reverts unconditionally. */ function _setPaused(bool paused) internal { if (paused) { _require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED); } else { _require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED); } _paused = paused; emit PausedStateChanged(paused); } /** * @dev Reverts if the contract is paused. */ function _ensureNotPaused() internal view { _require(_isNotPaused(), Errors.PAUSED); } /** * @dev Reverts if the contract is not paused. */ function _ensurePaused() internal view { _require(!_isNotPaused(), Errors.NOT_PAUSED); } /** * @dev Returns true if the contract is unpaused. * * Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no * longer accessed. */ function _isNotPaused() internal view returns (bool) { // After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access. return block.timestamp > _getBufferPeriodEndTime() || !_paused; } // These getters lead to reduced bytecode size by inlining the immutable variables in a single place. function _getPauseWindowEndTime() private view returns (uint256) { return _pauseWindowEndTime; } function _getBufferPeriodEndTime() private view returns (uint256) { return _bufferPeriodEndTime; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in * a single storage slot, saving gas by performing less storage accesses. * * Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two * 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128. * * We could use Solidity structs to pack values together in a single storage slot instead of relying on a custom and * error-prone library, but unfortunately Solidity only allows for structs to live in either storage, calldata or * memory. Because a memory struct uses not just memory but also a slot in the stack (to store its memory location), * using memory for word-sized values (i.e. of 256 bits or less) is strictly less gas performant, and doesn't even * prevent stack-too-deep issues. This is compounded by the fact that Balancer contracts typically are memory-intensive, * and the cost of accesing memory increases quadratically with the number of allocated words. Manual packing and * unpacking is therefore the preferred approach. */ library WordCodec { // Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word, // or to insert a new one replacing the old. uint256 private constant _MASK_1 = 2**(1) - 1; uint256 private constant _MASK_5 = 2**(5) - 1; uint256 private constant _MASK_7 = 2**(7) - 1; uint256 private constant _MASK_10 = 2**(10) - 1; uint256 private constant _MASK_16 = 2**(16) - 1; uint256 private constant _MASK_22 = 2**(22) - 1; uint256 private constant _MASK_31 = 2**(31) - 1; uint256 private constant _MASK_32 = 2**(32) - 1; uint256 private constant _MASK_53 = 2**(53) - 1; uint256 private constant _MASK_64 = 2**(64) - 1; uint256 private constant _MASK_96 = 2**(96) - 1; uint256 private constant _MASK_128 = 2**(128) - 1; uint256 private constant _MASK_192 = 2**(192) - 1; // Largest positive values that can be represented as N bits signed integers. int256 private constant _MAX_INT_22 = 2**(21) - 1; int256 private constant _MAX_INT_53 = 2**(52) - 1; // In-place insertion /** * @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new * word. */ function insertBool( bytes32 word, bool value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_1 << offset)); return clearedWord | bytes32(uint256(value ? 1 : 0) << offset); } // Unsigned /** * @dev Inserts a 5 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 5 bits, otherwise it may overwrite sibling bytes. */ function insertUint5( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_5 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 7 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 7 bits, otherwise it may overwrite sibling bytes. */ function insertUint7( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_7 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 10 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 10 bits, otherwise it may overwrite sibling bytes. */ function insertUint10( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_10 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 16 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. * Returns the new word. * * Assumes `value` only uses its least significant 16 bits, otherwise it may overwrite sibling bytes. */ function insertUint16( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_16 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 31 bits. */ function insertUint31( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_31 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 32 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 32 bits, otherwise it may overwrite sibling bytes. */ function insertUint32( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_32 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 64 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 64 bits, otherwise it may overwrite sibling bytes. */ function insertUint64( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_64 << offset)); return clearedWord | bytes32(value << offset); } // Signed /** * @dev Inserts a 22 bits signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 22 bits. */ function insertInt22( bytes32 word, int256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_22 << offset)); // Integer values need masking to remove the upper bits of negative values. return clearedWord | bytes32((uint256(value) & _MASK_22) << offset); } // Bytes /** * @dev Inserts 192 bit shifted by an offset into a 256 bit word, replacing the old value. Returns the new word. * * Assumes `value` can be represented using 192 bits. */ function insertBits192( bytes32 word, bytes32 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_192 << offset)); return clearedWord | bytes32((uint256(value) & _MASK_192) << offset); } // Encoding // Unsigned /** * @dev Encodes an unsigned integer shifted by an offset. This performs no size checks: it is up to the caller to * ensure that the values are bounded. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeUint(uint256 value, uint256 offset) internal pure returns (bytes32) { return bytes32(value << offset); } // Signed /** * @dev Encodes a 22 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_22) << offset); } /** * @dev Encodes a 53 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt53(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_53) << offset); } // Decoding /** * @dev Decodes and returns a boolean shifted by an offset from a 256 bit word. */ function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool) { return (uint256(word >> offset) & _MASK_1) == 1; } // Unsigned /** * @dev Decodes and returns a 5 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint5(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_5; } /** * @dev Decodes and returns a 7 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint7(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_7; } /** * @dev Decodes and returns a 10 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint10(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_10; } /** * @dev Decodes and returns a 16 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint16(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_16; } /** * @dev Decodes and returns a 31 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint31(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_31; } /** * @dev Decodes and returns a 32 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint32(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_32; } /** * @dev Decodes and returns a 64 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint64(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_64; } /** * @dev Decodes and returns a 96 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint96(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_96; } /** * @dev Decodes and returns a 128 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint128(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_128; } // Signed /** * @dev Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_22); // In case the decoded value is greater than the max positive integer that can be represented with 22 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value; } /** * @dev Decodes and returns a 53 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt53(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_53); // In case the decoded value is greater than the max positive integer that can be represented with 53 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_53 ? (value | int256(~_MASK_53)) : value; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.sol"; import "./SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, Errors.ERC20_DECREASED_ALLOWANCE_BELOW_ZERO) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { _require(sender != address(0), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS); _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_BALANCE); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { _require(account != address(0), Errors.ERC20_BURN_FROM_ZERO_ADDRESS); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_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 { _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "./IProtocolFeesCollector.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (IProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IVault.sol"; import "./IPoolSwapStructs.sol"; /** * @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not * the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from * either IGeneralPool or IMinimalSwapInfoPool */ interface IBasePool is IPoolSwapStructs { /** * @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of * each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault. * The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect * the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`. * * Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join. * * `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account * designated to receive any benefits (typically pool shares). `balances` contains the total balances * for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as minting pool shares. */ function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts); /** * @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many * tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes * to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`, * as well as collect the reported amount in protocol fees, which the Pool should calculate based on * `protocolSwapFeePercentage`. * * Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share. * * `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account * to which the Vault will send the proceeds. `balances` contains the total token balances for each token * the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as burning pool shares. */ function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts); function getPoolId() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IAssetManager { /** * @notice Emitted when asset manager is rebalanced */ event Rebalance(bytes32 poolId); /** * @notice Sets the config */ function setConfig(bytes32 poolId, bytes calldata config) external; /** * Note: No function to read the asset manager config is included in IAssetManager * as the signature is expected to vary between asset manager implementations */ /** * @notice Returns the asset manager's token */ function getToken() external view returns (IERC20); /** * @return the current assets under management of this asset manager */ function getAUM(bytes32 poolId) external view returns (uint256); /** * @return poolCash - The up-to-date cash balance of the pool * @return poolManaged - The up-to-date managed balance of the pool */ function getPoolBalances(bytes32 poolId) external view returns (uint256 poolCash, uint256 poolManaged); /** * @return The difference in tokens between the target investment * and the currently invested amount (i.e. the amount that can be invested) */ function maxInvestableBalance(bytes32 poolId) external view returns (int256); /** * @notice Updates the Vault on the value of the pool's investment returns */ function updateBalanceOfPool(bytes32 poolId) external; /** * @notice Determines whether the pool should rebalance given the provided balances */ function shouldRebalance(uint256 cash, uint256 managed) external view returns (bool); /** * @notice Rebalances funds between the pool and the asset manager to maintain target investment percentage. * @param poolId - the poolId of the pool to be rebalanced * @param force - a boolean representing whether a rebalance should be forced even when the pool is near balance */ function rebalance(bytes32 poolId, bool force) external; /** * @notice allows an authorized rebalancer to remove capital to facilitate large withdrawals * @param poolId - the poolId of the pool to withdraw funds back to * @param amount - the amount of tokens to withdraw back to the pool */ function capitalOut(bytes32 poolId, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20Permit.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; /** * @title Highly opinionated token implementation * @author Balancer Labs * @dev * - Includes functions to increase and decrease allowance as a workaround * for the well-known issue with `approve`: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * - Allows for 'infinite allowance', where an allowance of 0xff..ff is not * decreased by calls to transferFrom * - Lets a token holder use `transferFrom` to send their own tokens, * without first setting allowance * - Emits 'Approval' events whenever allowance is changed by `transferFrom` * - Assigns infinite allowance for all token holders to the Vault */ contract BalancerPoolToken is ERC20Permit { IVault private immutable _vault; constructor( string memory tokenName, string memory tokenSymbol, IVault vault ) ERC20(tokenName, tokenSymbol) ERC20Permit(tokenName) { _vault = vault; } function getVault() public view returns (IVault) { return _vault; } // Overrides /** * @dev Override to grant the Vault infinite allowance, causing for Pool Tokens to not require approval. * * This is sound as the Vault already provides authorization mechanisms when initiation token transfers, which this * contract inherits. */ function allowance(address owner, address spender) public view override returns (uint256) { if (spender == address(getVault())) { return uint256(-1); } else { return super.allowance(owner, spender); } } /** * @dev Override to allow for 'infinite allowance' and let the token owner use `transferFrom` with no self-allowance */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { uint256 currentAllowance = allowance(sender, msg.sender); _require(msg.sender == sender || currentAllowance >= amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE); _transfer(sender, recipient, amount); if (msg.sender != sender && currentAllowance != uint256(-1)) { // Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount _approve(sender, msg.sender, currentAllowance - amount); } return true; } /** * @dev Override to allow decreasing allowance by more than the current amount (setting it to zero) */ function decreaseAllowance(address spender, uint256 amount) public override returns (bool) { uint256 currentAllowance = allowance(msg.sender, spender); if (amount >= currentAllowance) { _approve(msg.sender, spender, 0); } else { // No risk of underflow due to if condition _approve(msg.sender, spender, currentAllowance - amount); } return true; } // Internal functions function _mintPoolTokens(address recipient, uint256 amount) internal { _mint(recipient, amount); } function _burnPoolTokens(address sender, uint256 amount) internal { _burn(sender, amount); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/Authentication.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IAuthorizer.sol"; /** * @dev Base authorization layer implementation for Pools. * * The owner account can call some of the permissioned functions - access control of the rest is delegated to the * Authorizer. Note that this owner is immutable: more sophisticated permission schemes, such as multiple ownership, * granular roles, etc., could be built on top of this by making the owner a smart contract. * * Access control of all other permissioned functions is delegated to an Authorizer. It is also possible to delegate * control of *all* permissioned functions to the Authorizer by setting the owner address to `_DELEGATE_OWNER`. */ abstract contract BasePoolAuthorization is Authentication { address private immutable _owner; address private constant _DELEGATE_OWNER = 0xBA1BA1ba1BA1bA1bA1Ba1BA1ba1BA1bA1ba1ba1B; constructor(address owner) { _owner = owner; } function getOwner() public view returns (address) { return _owner; } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { if ((getOwner() != _DELEGATE_OWNER) && _isOwnerOnlyAction(actionId)) { // Only the owner can perform "owner only" actions, unless the owner is delegated. return msg.sender == getOwner(); } else { // Non-owner actions are always processed via the Authorizer, as "owner only" ones are when delegated. return _getAuthorizer().canPerform(actionId, account, address(this)); } } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual returns (bool); function _getAuthorizer() internal view virtual returns (IAuthorizer); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, Errors.SUB_OVERFLOW); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, uint256 errorCode) internal pure returns (uint256) { _require(b <= a, errorCode); uint256 c = a - b; return c; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; /** * @dev Interface for WETH9. * See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; import "./IAuthorizer.sol"; interface IProtocolFeesCollector { event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external; function setSwapFeePercentage(uint256 newSwapFeePercentage) external; function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external; function getSwapFeePercentage() external view returns (uint256); function getFlashLoanFeePercentage() external view returns (uint256); function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts); function getAuthorizer() external view returns (IAuthorizer); function vault() external view returns (IVault); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; interface IPoolSwapStructs { // This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and // IMinimalSwapInfoPool. // // This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or // 'given out') which indicates whether or not the amount sent by the pool is known. // // The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take // in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`. // // All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in // some Pools. // // `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than // one Pool. // // The meaning of `lastChangeBlock` depends on the Pool specialization: // - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total // balance. // - General: the last block in which *any* of the Pool's registered tokens changed its total balance. // // `from` is the origin address for the funds the Pool receives, and `to` is the destination address // where the Pool sends the outgoing tokens. // // `userData` is extra data provided by the caller - typically a signature from a trusted party. struct SwapRequest { IVault.SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; // Misc data bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ERC20.sol"; import "./IERC20Permit.sol"; import "./EIP712.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { mapping(address => uint256) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time _require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT); uint256 nonce = _nonces[owner]; bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, nonce, deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ecrecover(hash, v, r, s); _require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE); _nonces[owner] = nonce + 1; _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner]; } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _HASHED_NAME = keccak256(bytes(name)); _HASHED_VERSION = keccak256(bytes(version)); _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { // Silence state mutability warning without generating bytecode. // See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and // https://github.com/ethereum/solidity/issues/2691 this; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./IAuthentication.sol"; /** * @dev Building block for performing access control on external functions. * * This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied * to external functions to only make them callable by authorized accounts. * * Derived contracts must implement the `_canPerform` function, which holds the actual access control logic. */ abstract contract Authentication is IAuthentication { bytes32 private immutable _actionIdDisambiguator; /** * @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in * multi contract systems. * * There are two main uses for it: * - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers * unique. The contract's own address is a good option. * - if the contract belongs to a family that shares action identifiers for the same functions, an identifier * shared by the entire family (and no other contract) should be used instead. */ constructor(bytes32 actionIdDisambiguator) { _actionIdDisambiguator = actionIdDisambiguator; } /** * @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions. */ modifier authenticate() { _authenticateCaller(); _; } /** * @dev Reverts unless the caller is allowed to call the entry point function. */ function _authenticateCaller() internal view { bytes32 actionId = getActionId(msg.sig); _require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED); } function getActionId(bytes4 selector) public view override returns (bytes32) { // Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the // function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of // multiple contracts. return keccak256(abi.encodePacked(_actionIdDisambiguator, selector)); } function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthentication { /** * @dev Returns the action identifier associated with the external function described by `selector`. */ function getActionId(bytes4 selector) external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/helpers/BaseSplitCodeFactory.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; /** * @dev Same as `BasePoolFactory`, for Pools whose creation code is so large that the factory cannot hold it. */ abstract contract BasePoolSplitCodeFactory is BaseSplitCodeFactory { IVault private immutable _vault; mapping(address => bool) private _isPoolFromFactory; event PoolCreated(address indexed pool); constructor(IVault vault, bytes memory creationCode) BaseSplitCodeFactory(creationCode) { _vault = vault; } /** * @dev Returns the Vault's address. */ function getVault() public view returns (IVault) { return _vault; } /** * @dev Returns true if `pool` was created by this factory. */ function isPoolFromFactory(address pool) external view returns (bool) { return _isPoolFromFactory[pool]; } function _create(bytes memory constructorArgs) internal override returns (address) { address pool = super._create(constructorArgs); _isPoolFromFactory[pool] = true; emit PoolCreated(pool); return pool; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @dev Utility to create Pool factories for Pools that use the `TemporarilyPausable` contract. * * By calling `TemporarilyPausable`'s constructor with the result of `getPauseConfiguration`, all Pools created by this * factory will share the same Pause Window end time, after which both old and new Pools will not be pausable. */ contract FactoryWidePauseWindow { // This contract relies on timestamps in a similar way as `TemporarilyPausable` does - the same caveats apply. // solhint-disable not-rely-on-time uint256 private constant _INITIAL_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _BUFFER_PERIOD_DURATION = 30 days; // Time when the pause window for all created Pools expires, and the pause window duration of new Pools becomes // zero. uint256 private immutable _poolsPauseWindowEndTime; constructor() { _poolsPauseWindowEndTime = block.timestamp + _INITIAL_PAUSE_WINDOW_DURATION; } /** * @dev Returns the current `TemporarilyPausable` configuration that will be applied to Pools created by this * factory. * * `pauseWindowDuration` will decrease over time until it reaches zero, at which point both it and * `bufferPeriodDuration` will be zero forever, meaning deployed Pools will not be pausable. */ function getPauseConfiguration() public view returns (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { uint256 currentTime = block.timestamp; if (currentTime < _poolsPauseWindowEndTime) { // The buffer period is always the same since its duration is related to how much time is needed to respond // to a potential emergency. The Pause Window duration however decreases as the end time approaches. pauseWindowDuration = _poolsPauseWindowEndTime - currentTime; // No need for checked arithmetic. bufferPeriodDuration = _BUFFER_PERIOD_DURATION; } else { // After the end time, newly created Pools have no Pause Window, nor Buffer Period (since they are not // pausable in the first place). pauseWindowDuration = 0; bufferPeriodDuration = 0; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./BalancerErrors.sol"; import "./CodeDeployer.sol"; /** * @dev Base factory for contracts whose creation code is so large that the factory cannot hold it. This happens when * the contract's creation code grows close to 24kB. * * Note that this factory cannot help with contracts that have a *runtime* (deployed) bytecode larger than 24kB. */ abstract contract BaseSplitCodeFactory { // The contract's creation code is stored as code in two separate addresses, and retrieved via `extcodecopy`. This // means this factory supports contracts with creation code of up to 48kB. // We rely on inline-assembly to achieve this, both to make the entire operation highly gas efficient, and because // `extcodecopy` is not available in Solidity. // solhint-disable no-inline-assembly address private immutable _creationCodeContractA; uint256 private immutable _creationCodeSizeA; address private immutable _creationCodeContractB; uint256 private immutable _creationCodeSizeB; /** * @dev The creation code of a contract Foo can be obtained inside Solidity with `type(Foo).creationCode`. */ constructor(bytes memory creationCode) { uint256 creationCodeSize = creationCode.length; // We are going to deploy two contracts: one with approximately the first half of `creationCode`'s contents // (A), and another with the remaining half (B). // We store the lengths in both immutable and stack variables, since immutable variables cannot be read during // construction. uint256 creationCodeSizeA = creationCodeSize / 2; _creationCodeSizeA = creationCodeSizeA; uint256 creationCodeSizeB = creationCodeSize - creationCodeSizeA; _creationCodeSizeB = creationCodeSizeB; // To deploy the contracts, we're going to use `CodeDeployer.deploy()`, which expects a memory array with // the code to deploy. Note that we cannot simply create arrays for A and B's code by copying or moving // `creationCode`'s contents as they are expected to be very large (> 24kB), so we must operate in-place. // Memory: [ code length ] [ A.data ] [ B.data ] // Creating A's array is simple: we simply replace `creationCode`'s length with A's length. We'll later restore // the original length. bytes memory creationCodeA; assembly { creationCodeA := creationCode mstore(creationCodeA, creationCodeSizeA) } // Memory: [ A.length ] [ A.data ] [ B.data ] // ^ creationCodeA _creationCodeContractA = CodeDeployer.deploy(creationCodeA); // Creating B's array is a bit more involved: since we cannot move B's contents, we are going to create a 'new' // memory array starting at A's last 32 bytes, which will be replaced with B's length. We'll back-up this last // byte to later restore it. bytes memory creationCodeB; bytes32 lastByteA; assembly { // `creationCode` points to the array's length, not data, so by adding A's length to it we arrive at A's // last 32 bytes. creationCodeB := add(creationCode, creationCodeSizeA) lastByteA := mload(creationCodeB) mstore(creationCodeB, creationCodeSizeB) } // Memory: [ A.length ] [ A.data[ : -1] ] [ B.length ][ B.data ] // ^ creationCodeA ^ creationCodeB _creationCodeContractB = CodeDeployer.deploy(creationCodeB); // We now restore the original contents of `creationCode` by writing back the original length and A's last byte. assembly { mstore(creationCodeA, creationCodeSize) mstore(creationCodeB, lastByteA) } } /** * @dev Returns the two addresses where the creation code of the contract crated by this factory is stored. */ function getCreationCodeContracts() public view returns (address contractA, address contractB) { return (_creationCodeContractA, _creationCodeContractB); } /** * @dev Returns the creation code of the contract this factory creates. */ function getCreationCode() public view returns (bytes memory) { return _getCreationCodeWithArgs(""); } /** * @dev Returns the creation code that will result in a contract being deployed with `constructorArgs`. */ function _getCreationCodeWithArgs(bytes memory constructorArgs) private view returns (bytes memory code) { // This function exists because `abi.encode()` cannot be instructed to place its result at a specific address. // We need for the ABI-encoded constructor arguments to be located immediately after the creation code, but // cannot rely on `abi.encodePacked()` to perform concatenation as that would involve copying the creation code, // which would be prohibitively expensive. // Instead, we compute the creation code in a pre-allocated array that is large enough to hold *both* the // creation code and the constructor arguments, and then copy the ABI-encoded arguments (which should not be // overly long) right after the end of the creation code. // Immutable variables cannot be used in assembly, so we store them in the stack first. address creationCodeContractA = _creationCodeContractA; uint256 creationCodeSizeA = _creationCodeSizeA; address creationCodeContractB = _creationCodeContractB; uint256 creationCodeSizeB = _creationCodeSizeB; uint256 creationCodeSize = creationCodeSizeA + creationCodeSizeB; uint256 constructorArgsSize = constructorArgs.length; uint256 codeSize = creationCodeSize + constructorArgsSize; assembly { // First, we allocate memory for `code` by retrieving the free memory pointer and then moving it ahead of // `code` by the size of the creation code plus constructor arguments, and 32 bytes for the array length. code := mload(0x40) mstore(0x40, add(code, add(codeSize, 32))) // We now store the length of the code plus constructor arguments. mstore(code, codeSize) // Next, we concatenate the creation code stored in A and B. let dataStart := add(code, 32) extcodecopy(creationCodeContractA, dataStart, 0, creationCodeSizeA) extcodecopy(creationCodeContractB, add(dataStart, creationCodeSizeA), 0, creationCodeSizeB) } // Finally, we copy the constructorArgs to the end of the array. Unfortunately there is no way to avoid this // copy, as it is not possible to tell Solidity where to store the result of `abi.encode()`. uint256 constructorArgsDataPtr; uint256 constructorArgsCodeDataPtr; assembly { constructorArgsDataPtr := add(constructorArgs, 32) constructorArgsCodeDataPtr := add(add(code, 32), creationCodeSize) } _memcpy(constructorArgsCodeDataPtr, constructorArgsDataPtr, constructorArgsSize); } /** * @dev Deploys a contract with constructor arguments. To create `constructorArgs`, call `abi.encode()` with the * contract's constructor arguments, in order. */ function _create(bytes memory constructorArgs) internal virtual returns (address) { bytes memory creationCode = _getCreationCodeWithArgs(constructorArgs); address destination; assembly { destination := create(0, add(creationCode, 32), mload(creationCode)) } if (destination == address(0)) { // Bubble up inner revert reason // solhint-disable-next-line no-inline-assembly assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } return destination; } // From // https://github.com/Arachnid/solidity-stringutils/blob/b9a6f6615cf18a87a823cbc461ce9e140a61c305/src/strings.sol function _memcpy( uint256 dest, uint256 src, uint256 len ) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint256 mask = 256**(32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; /** * @dev Library used to deploy contracts with specific code. This can be used for long-term storage of immutable data as * contract code, which can be retrieved via the `extcodecopy` opcode. */ library CodeDeployer { // During contract construction, the full code supplied exists as code, and can be accessed via `codesize` and // `codecopy`. This is not the contract's final code however: whatever the constructor returns is what will be // stored as its code. // // We use this mechanism to have a simple constructor that stores whatever is appended to it. The following opcode // sequence corresponds to the creation code of the following equivalent Solidity contract, plus padding to make the // full code 32 bytes long: // // contract CodeDeployer { // constructor() payable { // uint256 size; // assembly { // size := sub(codesize(), 32) // size of appended data, as constructor is 32 bytes long // codecopy(0, 32, size) // copy all appended data to memory at position 0 // return(0, size) // return appended data for it to be stored as code // } // } // } // // More specifically, it is composed of the following opcodes (plus padding): // // [1] PUSH1 0x20 // [2] CODESIZE // [3] SUB // [4] DUP1 // [6] PUSH1 0x20 // [8] PUSH1 0x00 // [9] CODECOPY // [11] PUSH1 0x00 // [12] RETURN // // The padding is just the 0xfe sequence (invalid opcode). It is important as it lets us work in-place, avoiding // memory allocation and copying. bytes32 private constant _DEPLOYER_CREATION_CODE = 0x602038038060206000396000f3fefefefefefefefefefefefefefefefefefefe; /** * @dev Deploys a contract with `code` as its code, returning the destination address. * * Reverts if deployment fails. */ function deploy(bytes memory code) internal returns (address destination) { bytes32 deployerCreationCode = _DEPLOYER_CREATION_CODE; // We need to concatenate the deployer creation code and `code` in memory, but want to avoid copying all of // `code` (which could be quite long) into a new memory location. Therefore, we operate in-place using // assembly. // solhint-disable-next-line no-inline-assembly assembly { let codeLength := mload(code) // `code` is composed of length and data. We've already stored its length in `codeLength`, so we simply // replace it with the deployer creation code (which is exactly 32 bytes long). mstore(code, deployerCreationCode) // At this point, `code` now points to the deployer creation code immediately followed by `code`'s data // contents. This is exactly what the deployer expects to receive when created. destination := create(0, code, add(codeLength, 32)) // Finally, we restore the original length in order to not mutate `code`. mstore(code, codeLength) } // The create opcode returns the zero address when contract creation fails, so we revert if this happens. _require(destination != address(0), Errors.CODE_DEPLOYMENT_FAILED); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/BasePoolSplitCodeFactory.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/FactoryWidePauseWindow.sol"; import "./ERC4626LinearPool.sol"; contract ERC4626LinearPoolFactory is BasePoolSplitCodeFactory, FactoryWidePauseWindow { constructor(IVault vault) BasePoolSplitCodeFactory(vault, type(ERC4626LinearPool).creationCode) { // solhint-disable-previous-line no-empty-blocks } /** * @dev Deploys a new `ERC4626LinearPool`. */ function create( string memory name, string memory symbol, IERC20 mainToken, IERC4626 wrappedToken, uint256 upperTarget, uint256 swapFeePercentage, address owner ) external returns (LinearPool) { (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) = getPauseConfiguration(); LinearPool pool = ERC4626LinearPool( _create( abi.encode( getVault(), name, symbol, mainToken, wrappedToken, upperTarget, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) ) ); // LinearPools have a separate post-construction initialization step: we perform it here to // ensure deployment and initialization are atomic. pool.initialize(); return pool; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "@balancer-labs/v2-solidity-utils/contracts/misc/IERC4626.sol"; import "../LinearPool.sol"; contract ERC4626LinearPool is LinearPool { using Math for uint256; uint256 private immutable _rateScaleFactor; constructor( IVault vault, string memory name, string memory symbol, IERC20 mainToken, IERC4626 wrappedToken, uint256 upperTarget, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) LinearPool( vault, name, symbol, mainToken, wrappedToken, upperTarget, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // We do NOT enforce mainToken == wrappedToken.asset() even // though this is the expected behavior in most cases. Instead, // we assume a 1:1 relationship between mainToken and // wrappedToken.asset(), but they do not have to be the same // token. It is vitally important that this 1:1 relationship is // respected, or the pool will not function as intended. // // This allows for use cases where the wrappedToken is // double-wrapped into an ERC-4626 token. For example, consider // a linear pool whose goal is to pair DAI with aDAI. Because // aDAI is a rebasing token, it needs to be wrapped, and let's // say an ERC-4626 wrapper is chosen for compatibility with this // linear pool. Then wrappedToken.asset() will return aDAI, // whereas mainToken is DAI. But the 1:1 relationship holds, and // the pool is still valid. // _getWrappedTokenRate is scaled e18, so we may need to scale IERC4626.convertToAssets() uint256 wrappedTokenDecimals = ERC20(address(wrappedToken)).decimals(); uint256 mainTokenDecimals = ERC20(address(mainToken)).decimals(); // This is always positive because we only accept tokens with <= 18 decimals uint256 digitsDifference = Math.add(18, wrappedTokenDecimals).sub(mainTokenDecimals); _rateScaleFactor = 10**digitsDifference; } function _getWrappedTokenRate() internal view override returns (uint256) { IERC4626 wrappedToken = IERC4626(getWrappedToken()); // Main tokens per 1e18 wrapped token wei // decimals: main + (18 - wrapped) uint256 assetsPerShare = wrappedToken.convertToAssets(FixedPoint.ONE); // This function returns a 18 decimal fixed point number // assetsPerShare decimals: 18 + main - wrapped // _rateScaleFactor decimals: 18 - main + wrapped uint256 rate = assetsPerShare.mul(_rateScaleFactor).divDown(FixedPoint.ONE); return rate; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; interface IERC4626 is IERC20 { /** * @dev `caller` has exchanged `assets` for `shares`, and transferred those `shares` to `owner`. */ event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares); /** * @dev `caller` has exchanged `shares`, owned by `owner`, for `assets`, * and transferred those `assets` to `receiver`. */ event Withdraw( address indexed caller, address indexed receiver, address indexed owner, uint256 assets, uint256 shares ); /** * @dev Mints `shares` Vault shares to `receiver` by depositing exactly `amount` of underlying tokens. */ function deposit(uint256 assets, address receiver) external returns (uint256 shares); /** * @dev Burns exactly `shares` from `owner` and sends `assets` of underlying tokens to `receiver`. */ function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets); /** * @dev The address of the underlying token that the Vault uses for accounting, depositing, and withdrawing. */ function asset() external view returns (address); /** * @dev Total amount of the underlying asset that is “managed” by Vault. */ function totalAssets() external view returns (uint256); /** * @dev The amount of `assets` that the Vault would exchange for the amount * of `shares` provided, in an ideal scenario where all the conditions are met. */ function convertToAssets(uint256 shares) external view returns (uint256 assets); /** * @dev The amount of `shares` that the Vault would exchange for the amount * of `assets` provided, in an ideal scenario where all the conditions are met. */ function convertToShares(uint256 assets) external view returns (uint256 shares); }
Pack targets as two uint96 values into a single storage slot. This results in targets being capped to 96 bits, but that should be more than enough.
function _setTargets( IERC20 mainToken, uint256 lowerTarget, uint256 upperTarget ) private { _require(lowerTarget <= upperTarget, Errors.LOWER_GREATER_THAN_UPPER_TARGET); _require(upperTarget <= _MAX_UPPER_TARGET, Errors.UPPER_TARGET_TOO_HIGH); _setMiscData( WordCodec.encodeUint(lowerTarget, _LOWER_TARGET_OFFSET) | WordCodec.encodeUint(upperTarget, _UPPER_TARGET_OFFSET) ); emit TargetsSet(mainToken, lowerTarget, upperTarget); }
9,951,923
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IBaseFee interface IBaseFee { function basefee_global() external view returns (uint256); } // Part: IFarming interface IFarming { function massHarvest() external returns (uint256); // this is claiming our rewards } // Part: IStaking interface IStaking { function deposit(address tokenAddress, uint256 amount) external; // pass want as tokenAdress here function withdraw(address tokenAddress, uint256 amount) external; // pass want as tokenAdress here function emergencyWithdraw(address tokenAddress) external; // can only be done if the last withdraw was > 10 epochs before function balanceOf(address user, address token) external view returns (uint256); // how much of our want we have staked } // Part: IUniV3 interface IUniV3 { struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); } // Part: IUniswapV2Router02 interface IUniswapV2Router02 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/Math /** * @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); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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; } } // Part: yearn/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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"); } } } // Part: yearn/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: yearn/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.2"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // File: StrategyBarnDAOStaking.sol contract StrategyBarnDAOStaking is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ address public staking; // DAO staking contract address public farmingContract; // This is the rewards contract we claim from IERC20 public emissionToken; // this is the token we receive from staking uint256 public sellCounter; // track our sells uint256 public sellsPerEpoch; // number of sells we divide our claim up into // swap stuff address public constant uniswapv3 = 0xE592427A0AEce92De3Edee1F18E0157C05861564; address public constant sushiswapRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; bool public sellOnSushi; // determine if we sell partially on sushi or all on Uni v3 uint24 public uniWantFee; // this is equal to 0.3%, can change this later if a different path becomes more optimal uint256 public maxGasPrice; // this is the max gas price we want our keepers to pay for harvests/tends in gwei IERC20 public constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 public constant weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); string internal stratName; // we use this to be able to adjust our strategy's name bool internal isOriginal = true; /* ========== CONSTRUCTOR ========== */ constructor( address _vault, address _farmingContract, address _emissionToken, address _staking, string memory _name ) public BaseStrategy(_vault) { _initializeStrat(_farmingContract, _emissionToken, _staking, _name); } /* ========== CLONING ========== */ event Cloned(address indexed clone); // we use this to clone our original strategy to other vaults function cloneBarnDAOStrategy( address _vault, address _strategist, address _rewards, address _keeper, address _farmingContract, address _emissionToken, address _staking, string memory _name ) external returns (address newStrategy) { require(isOriginal); // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } StrategyBarnDAOStaking(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _farmingContract, _emissionToken, _staking, _name ); emit Cloned(newStrategy); } // this will only be called by the clone function above function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _farmingContract, address _emissionToken, address _staking, string memory _name ) public { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_farmingContract, _emissionToken, _staking, _name); } // this is called by our original strategy, as well as any clones function _initializeStrat( address _farmingContract, address _emissionToken, address _staking, string memory _name ) internal { // initialize variables minReportDelay = 0; maxReportDelay = 604800; // 7 days in seconds, if we hit this then harvestTrigger = True profitFactor = 1_000_000; debtThreshold = 1e18; // we shouldn't ever have debt, but set a bit of a buffer farmingContract = _farmingContract; sellsPerEpoch = 1; healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012); // health.ychad.eth emissionToken = IERC20(_emissionToken); staking = _staking; // set our strategy's name stratName = _name; // start off using sushi sellOnSushi = true; // set our swap fee for univ3 uniWantFee = 3000; // want is what we stake for emissions want.approve(address(staking), type(uint256).max); // add approvals on all tokens emissionToken.approve(sushiswapRouter, type(uint256).max); weth.approve(sushiswapRouter, type(uint256).max); usdc.approve(uniswapv3, type(uint256).max); // set our max gas price maxGasPrice = 100 * 1e9; } /* ========== VIEWS ========== */ function name() external view override returns (string memory) { return stratName; } function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } function balanceOfStaked() public view returns (uint256) { return IStaking(staking).balanceOf(address(this), address(want)); } function estimatedTotalAssets() public view override returns (uint256) { // look at our staked tokens and any free tokens sitting in the strategy return balanceOfStaked().add(balanceOfWant()); } /* ========== MUTATIVE FUNCTIONS ========== */ function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // claim our rewards if (sellCounter == 0) IFarming(farmingContract).massHarvest(); // if we have emissionToken to sell, then sell some of it uint256 _emissionTokenBalance = emissionToken.balanceOf(address(this)); if (_emissionTokenBalance > 0) { // sell some fraction of our rewards to avoid hitting too much slippage uint256 _toSell = _emissionTokenBalance.div(sellsPerEpoch.sub(sellCounter)); // sell our emissionToken if (_toSell > 0) { if (sellOnSushi) { // well sell mostly on Sushi _sellMostlyOnSushi(_toSell); } else { _sellMostlyOnUni(_toSell); } sellCounter = sellCounter.add(1); if (sellCounter == sellsPerEpoch) sellCounter = 0; } } // debtOustanding will only be > 0 in the event of revoking or lowering debtRatio of a strategy if (_debtOutstanding > 0) { // add in a check for > 0 as withdraw reverts with 0 amount if (balanceOfStaked() > 0) { IStaking(staking).withdraw( address(want), Math.min(balanceOfStaked(), _debtOutstanding) ); } uint256 _withdrawnBal = balanceOfWant(); _debtPayment = Math.min(_debtOutstanding, _withdrawnBal); } // serious loss should never happen, but if it does (for instance, if Curve is hacked), let's record it accurately uint256 assets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; // if assets are greater than debt, things are working great! if (assets > debt) { _profit = assets.sub(debt); uint256 _wantBal = balanceOfWant(); if (_profit.add(_debtPayment) > _wantBal) { // this should only be hit following donations to strategy liquidateAllPositions(); } } // if assets are less than debt, we are in trouble else { _loss = debt.sub(assets); } } // sell from want to USDC via sushi, USDC -> WETH via Uni, WETH -> want via Uni function _sellMostlyOnUni(uint256 _amount) internal { // sell our emission token for USDC on sushi address[] memory emissionTokenPath = new address[](2); emissionTokenPath[0] = address(emissionToken); emissionTokenPath[1] = address(usdc); IUniswapV2Router02(sushiswapRouter).swapExactTokensForTokens( _amount, uint256(0), emissionTokenPath, address(this), block.timestamp ); // sell our USDC for want through WETH on Uni uint256 _usdcBalance = usdc.balanceOf(address(this)); IUniV3(uniswapv3).exactInput( IUniV3.ExactInputParams( abi.encodePacked( address(usdc), uint24(500), address(weth), uint24(uniWantFee), address(want) ), address(this), block.timestamp, _usdcBalance, uint256(1) ) ); } // sell from want to USDC via sushi, USDC -> WETH via Uni, WETH -> want via Sushi function _sellMostlyOnSushi(uint256 _amount) internal { // sell our emission token for USDC on sushi address[] memory emissionTokenPath = new address[](2); emissionTokenPath[0] = address(emissionToken); emissionTokenPath[1] = address(usdc); IUniswapV2Router02(sushiswapRouter).swapExactTokensForTokens( _amount, uint256(0), emissionTokenPath, address(this), block.timestamp ); // sell our usdc for weth on uni uint256 _usdcBalance = usdc.balanceOf(address(this)); IUniV3(uniswapv3).exactInput( IUniV3.ExactInputParams( abi.encodePacked(address(usdc), uint24(500), address(weth)), address(this), block.timestamp, _usdcBalance, uint256(1) ) ); // sell our weth for want on sushi uint256 _wethBalance = weth.balanceOf(address(this)); address[] memory wantTokenPath = new address[](2); wantTokenPath[0] = address(weth); wantTokenPath[1] = address(want); IUniswapV2Router02(sushiswapRouter).swapExactTokensForTokens( _wethBalance, uint256(0), wantTokenPath, address(this), block.timestamp ); } function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit) { return; } // send all of our want tokens to be deposited uint256 _toInvest = balanceOfWant(); // stake only if we have something to stake if (_toInvest > 0) { IStaking(staking).deposit(address(want), _toInvest); } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 _wantBal = balanceOfWant(); if (_amountNeeded > _wantBal) { uint256 _stakedBal = balanceOfStaked(); // add in a check for > 0 as withdraw reverts with 0 amount if (_stakedBal > 0) { IStaking(staking).withdraw( address(want), Math.min(_stakedBal, _amountNeeded.sub(_wantBal)) ); } uint256 _withdrawnBal = balanceOfWant(); _liquidatedAmount = Math.min(_amountNeeded, _withdrawnBal); _loss = _amountNeeded.sub(_liquidatedAmount); } else { // we have enough balance to cover the liquidation available return (_amountNeeded, 0); } } function liquidateAllPositions() internal override returns (uint256) { uint256 _stakedBal = balanceOfStaked(); if (_stakedBal > 0) { IStaking(staking).withdraw(address(want), _stakedBal); } return balanceOfWant(); } // only do this if absolutely necessary; as rewards won't be claimed, and this also must be 10 weeks after our last withdrawal. this will revert if we don't have anything to withdraw. function emergencyWithdraw() external onlyEmergencyAuthorized { IStaking(staking).emergencyWithdraw(address(want)); } function prepareMigration(address _newStrategy) internal override { uint256 _stakedBal = balanceOfStaked(); if (_stakedBal > 0) { IStaking(staking).withdraw(address(want), _stakedBal); } // send our claimed emissionToken to the new strategy emissionToken.safeTransfer( _newStrategy, emissionToken.balanceOf(address(this)) ); } function protectedTokens() internal view override returns (address[] memory) {} // our main trigger is regarding our DCA since there is low liquidity for our emissionToken function harvestTrigger(uint256 callCostinEth) public view override returns (bool) { // Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job. if (!isActive()) return false; // check if the base fee gas price is higher than we allow if (readBaseFee() > maxGasPrice) { return false; } return super.harvestTrigger(callCostinEth); } function ethToWant(uint256 _amtInWei) public view override returns (uint256) { uint256 _ethToWant; if (_amtInWei > 0) { address[] memory ethPath = new address[](2); ethPath[0] = address(weth); ethPath[1] = address(want); uint256[] memory callCostInWant = IUniswapV2Router02(sushiswapRouter).getAmountsOut( _amtInWei, ethPath ); _ethToWant = callCostInWant[callCostInWant.length - 1]; } return _ethToWant; } function readBaseFee() internal view returns (uint256 baseFee) { IBaseFee _baseFeeOracle = IBaseFee(0xf8d0Ec04e94296773cE20eFbeeA82e76220cD549); return _baseFeeOracle.basefee_global(); } /* ========== SETTERS ========== */ // set number of batches we sell our claimed emissionToken in function setSellsPerEpoch(uint256 _sellsPerEpoch) external onlyEmergencyAuthorized { require( 15 > _sellsPerEpoch && _sellsPerEpoch > 0, "Must be above 0 and less than 15" ); sellsPerEpoch = _sellsPerEpoch; // reset our counter to be safe sellCounter = 0; } // set the maximum gas price we want to pay for a harvest/tend in gwei function setGasPrice(uint256 _maxGasPrice) external onlyAuthorized { maxGasPrice = _maxGasPrice.mul(1e9); } // set the fee pool we'd like to swap through for if we're swapping from ETH to want on UniV3 function setUniWantFee(uint24 _fee) external onlyAuthorized { uniWantFee = _fee; } // set if we want to sell our swap partly on sushi or just uniV3 function setSellOnSushi(bool _sellOnSushi) external onlyAuthorized { sellOnSushi = _sellOnSushi; } }
this is claiming our rewards
function massHarvest() external returns (uint256);
1,406,948
./full_match/5/0xB78299e5183C7746D825D9f92ABF6368F54f8537/sources/contracts/y00tsAnchorClub.sol
ERC721 token receiver interface Interface for any contract that wants to support safeTransfers from ERC721 asset contracts./
interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns(bytes4); }
1,879,451
./full_match/11155111/0xE46FE78DBfCa5E835667Ba9dCd3F3315E7623F8a/sources/contracts/SignatureDecoder.sol
divides bytes signature into `uint8 v, bytes32 r, bytes32 s`. Make sure to peform a bounds check for pos, to avoid out of bounds access on signatures pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access signatures concatenated rsv signatures The signature format is a compact form of: {bytes32 r}{bytes32 s}{uint8 v} Compact means, uint8 is not padded to 32 bytes. solium-disable-next-line security/no-inline-assembly Here we are loading the last 32 bytes, including 31 bytes of 's'. There is no 'mload8' to do this. 'byte' is not working due to the Solidity parser, so lets use the second best option, 'and'
function signatureSplit(bytes memory signatures, uint256 pos) internal pure returns (uint8 v, bytes32 r, bytes32 s) { assembly { let signaturePos := mul(0x41, pos) r := mload(add(signatures, add(signaturePos, 0x20))) s := mload(add(signatures, add(signaturePos, 0x40))) v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff) } }
3,835,110
./partial_match/4/0x5417c147643c6380758c69b7f1aEfb4974E1a34F/sources/ArbOne.sol
返回我参与第二轮仲裁订单列表 @count 最多返回的数量
function applDeal(address usr, uint256 count) external view returns (UserInfo[] memory) { uint length = appl[usr]; if (count < length) length = count; UserInfo[] memory result = new UserInfo[](length); uint max = appl[usr]; uint j; for (uint i = max; i >=1 ; --i) { uint n = register[usr][i]; UserInfo memory m = user[n]; result[j] = m; j +=1; if (i-1 == max-length) break; } return result; }
16,994,131
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma abicoder v2; import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {ECDSA} from '@openzeppelin/contracts/cryptography/ECDSA.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol'; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import {IHypervisor} from './interfaces/IHypervisor.sol'; import {IBabController} from './interfaces/IBabController.sol'; import {IGovernor} from './interfaces/external/oz/IGovernor.sol'; import {IGarden} from './interfaces/IGarden.sol'; import {IHeart} from './interfaces/IHeart.sol'; import {IWETH} from './interfaces/external/weth/IWETH.sol'; import {ICToken} from './interfaces/external/compound/ICToken.sol'; import {ICEther} from './interfaces/external/compound/ICEther.sol'; import {IComptroller} from './interfaces/external/compound/IComptroller.sol'; import {IPriceOracle} from './interfaces/IPriceOracle.sol'; import {IMasterSwapper} from './interfaces/IMasterSwapper.sol'; import {IVoteToken} from './interfaces/IVoteToken.sol'; import {IERC1271} from './interfaces/IERC1271.sol'; import {PreciseUnitMath} from './lib/PreciseUnitMath.sol'; import {SafeDecimalMath} from './lib/SafeDecimalMath.sol'; import {LowGasSafeMath as SafeMath} from './lib/LowGasSafeMath.sol'; import {Errors, _require, _revert} from './lib/BabylonErrors.sol'; import {ControllerLib} from './lib/ControllerLib.sol'; /** * @title Heart * @author Babylon Finance * * Contract that assists The Heart of Babylon garden with BABL staking. * */ contract Heart is OwnableUpgradeable, IHeart, IERC1271 { using SafeERC20 for IERC20; using PreciseUnitMath for uint256; using SafeMath for uint256; using SafeDecimalMath for uint256; using ControllerLib for IBabController; /* ============ Modifiers ============ */ /** * Throws if the sender is not a keeper in the protocol */ function _onlyKeeper() private view { _require(controller.isValidKeeper(msg.sender), Errors.ONLY_KEEPER); } /* ============ Events ============ */ event FeesCollected(uint256 _timestamp, uint256 _amount); event LiquidityAdded(uint256 _timestamp, uint256 _wethBalance, uint256 _bablBalance); event BablBuyback(uint256 _timestamp, uint256 _wethSpent, uint256 _bablBought); event GardenSeedInvest(uint256 _timestamp, address indexed _garden, uint256 _wethInvested); event FuseLentAsset(uint256 _timestamp, address indexed _asset, uint256 _assetAmount); event BABLRewardSent(uint256 _timestamp, uint256 _bablSent); event ProposalVote(uint256 _timestamp, uint256 _proposalId, bool _isApprove); event UpdatedGardenWeights(uint256 _timestamp); /* ============ Constants ============ */ // Only for offline use by keeper/fauna bytes32 private constant VOTE_PROPOSAL_TYPEHASH = keccak256('ProposalVote(uint256 _proposalId,uint256 _amount,bool _isApprove)'); bytes32 private constant VOTE_GARDEN_TYPEHASH = keccak256('GardenVote(address _garden,uint256 _amount)'); // Visor IHypervisor private constant visor = IHypervisor(0xF19F91d7889668A533F14d076aDc187be781a458); // Address of Uniswap factory IUniswapV3Factory internal constant factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); uint24 private constant FEE_LOW = 500; uint24 private constant FEE_MEDIUM = 3000; uint24 private constant FEE_HIGH = 10000; uint256 private constant DEFAULT_TRADE_SLIPPAGE = 25e15; // 2.5% // Tokens IWETH private constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IERC20 private constant BABL = IERC20(0xF4Dc48D260C93ad6a96c5Ce563E70CA578987c74); IERC20 private constant DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20 private constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 private constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); IERC20 private constant FRAX = IERC20(0x853d955aCEf822Db058eb8505911ED77F175b99e); IERC20 private constant FEI = IERC20(0x956F47F50A910163D8BF957Cf5846D573E7f87CA); // Fuse address private constant BABYLON_FUSE_POOL_ADDRESS = 0xC7125E3A2925877C7371d579D29dAe4729Ac9033; // Value Amount for protect purchases in DAI uint256 private constant PROTECT_BUY_AMOUNT_DAI = 2e21; /* ============ Immutables ============ */ IBabController private immutable controller; IGovernor private immutable governor; address private immutable treasury; /* ============ State Variables ============ */ // Instance of the Controller contract // Heart garden address IGarden public override heartGarden; // Variables to handle garden seed investments address[] public override votedGardens; uint256[] public override gardenWeights; // Min Amounts to trade mapping(address => uint256) public override minAmounts; // Fuse pool Variables // Mapping of asset addresses to cToken addresses in the fuse pool mapping(address => address) public override assetToCToken; // Which asset is going to receive the next batch of liquidity in fuse address public override assetToLend; // Timestamp when the heart was last pumped uint256 public override lastPumpAt; // Timestamp when the votes were sent by the keeper last uint256 public override lastVotesAt; // Amount to gift to the Heart of Babylon Garden weekly uint256 public override weeklyRewardAmount; uint256 public override bablRewardLeft; // Array with the weights to distribute to different heart activities // 0: Treasury // 1: Buybacks // 2: Liquidity BABL-ETH // 3: Garden Seed Investments // 4: Fuse Pool uint256[] public override feeDistributionWeights; // Metric Totals // 0: fees accumulated in weth // 1: Money sent to treasury // 2: babl bought in babl // 3: liquidity added in weth // 4: amount invested in gardens in weth // 5: amount lent on fuse in weth // 6: weekly rewards paid in babl uint256[7] public override totalStats; // Trade slippage to apply in trades uint256 public override tradeSlippage; // Asset to use to buy protocol wanted assets address public override assetForPurchases; // Bond Assets with the discount mapping(address => uint256) public override bondAssets; // EIP-1271 signer address private signer; uint256 private constant MIN_PUMP_WETH = 15e17; // 1.5 ETH /* ============ Initializer ============ */ /** * Set controller and governor addresses * * @param _controller Address of controller contract * @param _governor Address of governor contract */ constructor(IBabController _controller, IGovernor _governor) initializer { _require(address(_controller) != address(0), Errors.ADDRESS_IS_ZERO); _require(address(_governor) != address(0), Errors.ADDRESS_IS_ZERO); controller = _controller; treasury = _controller.treasury(); governor = _governor; } /** * Set state variables and map asset pairs to their oracles * * @param _feeWeights Weights of the fee distribution */ function initialize(uint256[] calldata _feeWeights) external initializer { OwnableUpgradeable.__Ownable_init(); updateFeeWeights(_feeWeights); updateMarkets(); updateAssetToLend(address(DAI)); minAmounts[address(DAI)] = 500e18; minAmounts[address(USDC)] = 500e6; minAmounts[address(WETH)] = 5e17; minAmounts[address(WBTC)] = 3e6; // Self-delegation to be able to use BABL balance as voting power IVoteToken(address(BABL)).delegate(address(this)); tradeSlippage = DEFAULT_TRADE_SLIPPAGE; } /* ============ External Functions ============ */ /** * Function to pump blood to the heart * * Note: Anyone can call this. Keeper in Defender will be set up to do it for convenience. */ function pump() public override { _require(address(heartGarden) != address(0), Errors.HEART_GARDEN_NOT_SET); _require(block.timestamp.sub(lastPumpAt) >= 1 weeks, Errors.HEART_ALREADY_PUMPED); _require(block.timestamp.sub(lastVotesAt) < 1 weeks, Errors.HEART_VOTES_MISSING); // Consolidate all fees _consolidateFeesToWeth(); uint256 wethBalance = WETH.balanceOf(address(this)); // Use fei to pump if needed if (wethBalance < MIN_PUMP_WETH) { uint256 feiPriceInWeth = IPriceOracle(controller.priceOracle()).getPrice(address(FEI), address(WETH)); uint256 feiNeeded = MIN_PUMP_WETH.sub(wethBalance).preciseMul(feiPriceInWeth).preciseMul(105e16); // a bit more just in case if (FEI.balanceOf(address(this)) >= feiNeeded) { _trade(address(FEI), address(WETH), feiNeeded); } } _require(wethBalance >= 15e17, Errors.HEART_MINIMUM_FEES); // Send 10% to the treasury IERC20(WETH).safeTransferFrom(address(this), treasury, wethBalance.preciseMul(feeDistributionWeights[0])); totalStats[1] = totalStats[1].add(wethBalance.preciseMul(feeDistributionWeights[0])); // 30% for buybacks _buyback(wethBalance.preciseMul(feeDistributionWeights[1])); // 25% to BABL-ETH pair _addLiquidity(wethBalance.preciseMul(feeDistributionWeights[2])); // 15% to Garden Investments _investInGardens(wethBalance.preciseMul(feeDistributionWeights[3])); // 20% lend in fuse pool _lendFusePool(address(WETH), wethBalance.preciseMul(feeDistributionWeights[4]), address(assetToLend)); // Add BABL reward to stakers (if any) _sendWeeklyReward(); lastPumpAt = block.timestamp; } /** * Function to vote for a proposal * * Note: Only keeper can call this. Votes need to have been resolved offchain. * Warning: Gardens need to delegate to heart first. */ function voteProposal(uint256 _proposalId, bool _isApprove) external override { _onlyKeeper(); // Governor does revert if trying to cast a vote twice or if proposal is not active IGovernor(governor).castVote(_proposalId, _isApprove ? 1 : 0); emit ProposalVote(block.timestamp, _proposalId, _isApprove); } /** * Resolves garden votes for this cycle * * Note: Only keeper can call this * @param _gardens Gardens that are going to receive investment * @param _weights Weight for the investment in each garden normalied to 1e18 precision */ function resolveGardenVotes(address[] memory _gardens, uint256[] memory _weights) public override { _onlyKeeper(); _require(_gardens.length == _weights.length, Errors.HEART_VOTES_LENGTH); delete votedGardens; delete gardenWeights; for (uint256 i = 0; i < _gardens.length; i++) { votedGardens.push(_gardens[i]); gardenWeights.push(_weights[i]); } lastVotesAt = block.timestamp; emit UpdatedGardenWeights(block.timestamp); } function resolveGardenVotesAndPump(address[] memory _gardens, uint256[] memory _weights) external override { resolveGardenVotes(_gardens, _weights); pump(); } /** * Updates fuse pool market information and enters the markets * */ function updateMarkets() public override { controller.onlyGovernanceOrEmergency(); // Enter markets of the fuse pool for all these assets address[] memory markets = IComptroller(BABYLON_FUSE_POOL_ADDRESS).getAllMarkets(); for (uint256 i = 0; i < markets.length; i++) { address underlying = ICToken(markets[i]).underlying(); assetToCToken[underlying] = markets[i]; } IComptroller(BABYLON_FUSE_POOL_ADDRESS).enterMarkets(markets); } /** * Set the weights to allocate to different heart initiatives * * @param _feeWeights Array of % (up to 1e18) with the fee weights */ function updateFeeWeights(uint256[] calldata _feeWeights) public override { controller.onlyGovernanceOrEmergency(); delete feeDistributionWeights; for (uint256 i = 0; i < _feeWeights.length; i++) { feeDistributionWeights.push(_feeWeights[i]); } } /** * Updates the next asset to lend on fuse pool * * @param _assetToLend New asset to lend */ function updateAssetToLend(address _assetToLend) public override { controller.onlyGovernanceOrEmergency(); _require(assetToLend != _assetToLend, Errors.HEART_ASSET_LEND_SAME); _require(assetToCToken[_assetToLend] != address(0), Errors.HEART_ASSET_LEND_INVALID); assetToLend = _assetToLend; } /** * Updates the next asset to purchase assets from strategies at a premium * * @param _purchaseAsset New asset to purchase */ function updateAssetToPurchase(address _purchaseAsset) public override { controller.onlyGovernanceOrEmergency(); _require( _purchaseAsset != assetForPurchases && _purchaseAsset != address(0), Errors.HEART_ASSET_PURCHASE_INVALID ); assetForPurchases = _purchaseAsset; } /** * Updates the next asset to purchase assets from strategies at a premium * * @param _assetToBond Bond to update * @param _bondDiscount Bond discount to apply 1e18 */ function updateBond(address _assetToBond, uint256 _bondDiscount) public override { controller.onlyGovernanceOrEmergency(); bondAssets[_assetToBond] = _bondDiscount; } /** * Adds a BABL reward to be distributed weekly back to the heart garden * * @param _bablAmount Total amount to distribute * @param _weeklyRate Weekly amount to distribute */ function addReward(uint256 _bablAmount, uint256 _weeklyRate) external override { controller.onlyGovernanceOrEmergency(); // Get the BABL reward IERC20(BABL).safeTransferFrom(msg.sender, address(this), _bablAmount); bablRewardLeft = bablRewardLeft.add(_bablAmount); weeklyRewardAmount = _weeklyRate; } /** * Updates the min amount to trade a specific asset * * @param _asset Asset to edit the min amount * @param _minAmountOut New min amount */ function setMinTradeAmount(address _asset, uint256 _minAmountOut) external override { controller.onlyGovernanceOrEmergency(); minAmounts[_asset] = _minAmountOut; } /** * Updates the heart garden address * * @param _heartGarden New heart garden address */ function setHeartGardenAddress(address _heartGarden) external override { controller.onlyGovernanceOrEmergency(); heartGarden = IGarden(_heartGarden); } /** * Updates the tradeSlippage * * @param _tradeSlippage Trade slippage */ function setTradeSlippage(uint256 _tradeSlippage) external override { controller.onlyGovernanceOrEmergency(); tradeSlippage = _tradeSlippage; } /** * Tell the heart to lend an asset on Fuse * * @param _assetToLend Address of the asset to lend * @param _lendAmount Amount of the asset to lend */ function lendFusePool(address _assetToLend, uint256 _lendAmount) external override { controller.onlyGovernanceOrEmergency(); // Lend into fuse _lendFusePool(_assetToLend, _lendAmount, _assetToLend); } /** * Heart borrows using its liquidity * Note: Heart must have enough liquidity * * @param _assetToBorrow Asset that the heart is receiving from sender * @param _borrowAmount Amount of asset to transfet */ function borrowFusePool(address _assetToBorrow, uint256 _borrowAmount) external override { controller.onlyGovernanceOrEmergency(); address cToken = assetToCToken[_assetToBorrow]; _require(cToken != address(0), Errors.HEART_INVALID_CTOKEN); _require(ICToken(cToken).borrow(_borrowAmount) == 0, Errors.NOT_ENOUGH_COLLATERAL); } /** * Repays Heart fuse pool position * Note: We must have the asset in the heart * * @param _borrowedAsset Borrowed asset that we want to pay * @param _amountToRepay Amount of asset to transfer */ function repayFusePool(address _borrowedAsset, uint256 _amountToRepay) external override { controller.onlyGovernanceOrEmergency(); address cToken = assetToCToken[_borrowedAsset]; IERC20(_borrowedAsset).safeApprove(cToken, _amountToRepay); _require(ICToken(cToken).repayBorrow(_amountToRepay) == 0, Errors.AMOUNT_TOO_LOW); } /** * Trades one asset for another in the heart * Note: We must have the _fromAsset _fromAmount available. * @param _fromAsset Asset to exchange * @param _toAsset Asset to receive * @param _fromAmount Amount of asset to exchange * @param _minAmountOut Min amount of received asset */ function trade( address _fromAsset, address _toAsset, uint256 _fromAmount, uint256 _minAmountOut ) external override { controller.onlyGovernanceOrEmergency(); _require(IERC20(_fromAsset).balanceOf(address(this)) >= _fromAmount, Errors.AMOUNT_TOO_LOW); uint256 boughtAmount = _trade(_fromAsset, _toAsset, _fromAmount); _require(boughtAmount >= _minAmountOut, Errors.SLIPPAGE_TOO_HIH); } /** * Strategies can sell wanted assets by the protocol to the heart. * Heart will buy them using borrowings in stables. * Heart returns WETH so master swapper will take it from there. * Note: Strategy needs to have approved the heart. * * @param _assetToSell Asset that the heart is receiving from strategy to sell * @param _amountToSell Amount of asset to sell */ function sellWantedAssetToHeart(address _assetToSell, uint256 _amountToSell) external override { _require(controller.isSystemContract(msg.sender), Errors.NOT_A_SYSTEM_CONTRACT); _require(controller.protocolWantedAssets(_assetToSell), Errors.HEART_ASSET_PURCHASE_INVALID); _require(assetForPurchases != address(0), Errors.INVALID_ADDRESS); // Uses on chain oracle to fetch prices uint256 pricePerTokenUnit = IPriceOracle(controller.priceOracle()).getPrice(_assetToSell, assetForPurchases); _require(pricePerTokenUnit != 0, Errors.NO_PRICE_FOR_TRADE); uint256 amountInPurchaseAssetOffered = pricePerTokenUnit.preciseMul(_amountToSell); _require( IERC20(assetForPurchases).balanceOf(address(this)) >= amountInPurchaseAssetOffered, Errors.BALANCE_TOO_LOW ); IERC20(_assetToSell).safeTransferFrom(msg.sender, address(this), _amountToSell); // Buy it from the strategy plus 1% premium uint256 wethTraded = _trade(assetForPurchases, address(WETH), amountInPurchaseAssetOffered.preciseMul(101e16)); // Send weth back to the strategy IERC20(WETH).safeTransfer(msg.sender, wethTraded); } /** * Users can bond an asset that belongs to the program and receive a discount on hBABL. * Note: Heart needs to have enough BABL to satisfy the discount. * Note: User needs to approve the asset to bond first. * * @param _assetToBond Asset that the user wants to bond * @param _amountToBond Amount to be bonded * @param _minAmountOut Min amount of Heart garden shares to recieve */ function bondAsset( address _assetToBond, uint256 _amountToBond, uint256 _minAmountOut, address _referrer ) external override { _require(bondAssets[_assetToBond] > 0 && _amountToBond > 0, Errors.AMOUNT_TOO_LOW); // Total value adding the premium uint256 bondValueInBABL = _bondToBABL( _assetToBond, _amountToBond, IPriceOracle(controller.priceOracle()).getPrice(_assetToBond, address(BABL)) ); // Get asset to bond from sender IERC20(_assetToBond).safeTransferFrom(msg.sender, address(this), _amountToBond); // Deposit on behalf of the user _require(BABL.balanceOf(address(this)) >= bondValueInBABL, Errors.AMOUNT_TOO_LOW); BABL.safeApprove(address(heartGarden), bondValueInBABL); heartGarden.deposit(bondValueInBABL, _minAmountOut, msg.sender, _referrer); } /** * Users can bond an asset that belongs to the program and receive a discount on hBABL. * Note: Heart needs to have enough BABL to satisfy the discount. * Note: User needs to approve the asset to bond first. * * @param _assetToBond Asset that the user wants to bond * @param _amountToBond Amount to be bonded */ function bondAssetBySig( address _assetToBond, uint256 _amountToBond, uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, uint256 _priceInBABL, uint256 _pricePerShare, uint256 _fee, address _contributor, address _referrer, bytes memory _signature ) external override { _onlyKeeper(); _require(_fee <= _maxFee, Errors.FEE_TOO_HIGH); _require(bondAssets[_assetToBond] > 0 && _amountToBond > 0, Errors.AMOUNT_TOO_LOW); // Get asset to bond from contributor IERC20(_assetToBond).safeTransferFrom(_contributor, address(this), _amountToBond); // Deposit on behalf of the user _require(BABL.balanceOf(address(this)) >= _amountIn, Errors.AMOUNT_TOO_LOW); // verify that _amountIn is correct compare to _amountToBond uint256 val = _bondToBABL(_assetToBond, _amountToBond, _priceInBABL); uint256 diff = val > _amountIn ? val.sub(_amountIn) : _amountIn.sub(val); // allow 0.1% deviation _require(diff < _amountIn.div(1000), Errors.INVALID_AMOUNT); BABL.safeApprove(address(heartGarden), _amountIn); // Pay the fee to the Keeper IERC20(BABL).safeTransfer(msg.sender, _fee); // grant permission to deposit signer = _contributor; heartGarden.depositBySig( _amountIn, _minAmountOut, _nonce, _maxFee, _contributor, _pricePerShare, 0, address(this), _referrer, _signature ); // revoke permission to deposit signer = address(0); } /** * Heart will protect and buyback BABL whenever the price dips below the intended price protection. * Note: Asset for purchases needs to be setup and have enough balance. * * @param _bablPriceProtectionAt BABL Price in DAI to protect * @param _bablPrice Market price of BABL in DAI * @param _purchaseAssetPrice Price of purchase asset in DAI * @param _slippage Trade slippage on UinV3 to control amount of arb * @param _hopToken Hop token to use for UniV3 trade */ function protectBABL( uint256 _bablPriceProtectionAt, uint256 _bablPrice, uint256 _purchaseAssetPrice, uint256 _slippage, address _hopToken ) external override { _onlyKeeper(); _require(assetForPurchases != address(0), Errors.HEART_ASSET_PURCHASE_INVALID); _require(_bablPriceProtectionAt > 0 && _bablPrice <= _bablPriceProtectionAt, Errors.AMOUNT_TOO_HIGH); _require( SafeDecimalMath.normalizeAmountTokens( assetForPurchases, address(DAI), _purchaseAssetPrice.preciseMul(IERC20(assetForPurchases).balanceOf(address(this))) ) >= PROTECT_BUY_AMOUNT_DAI, Errors.NOT_ENOUGH_AMOUNT ); uint256 exactAmount = PROTECT_BUY_AMOUNT_DAI.preciseDiv(_bablPrice); uint256 minAmountOut = exactAmount.sub(exactAmount.preciseMul(_slippage == 0 ? tradeSlippage : _slippage)); uint256 bablBought = _trade( assetForPurchases, address(BABL), SafeDecimalMath.normalizeAmountTokens( address(DAI), assetForPurchases, PROTECT_BUY_AMOUNT_DAI.preciseDiv(_purchaseAssetPrice) ), minAmountOut, _hopToken != address(0) ? _hopToken : address(WETH) ); totalStats[2] = totalStats[2].add(bablBought); emit BablBuyback(block.timestamp, PROTECT_BUY_AMOUNT_DAI, bablBought); } // solhint-disable-next-line receive() external payable {} /* ============ External View Functions ============ */ /** * Getter to get the whole array of voted gardens * * @return The array of voted gardens */ function getVotedGardens() external view override returns (address[] memory) { return votedGardens; } /** * Getter to get the whole array of garden weights * * @return The array of weights for voted gardens */ function getGardenWeights() external view override returns (uint256[] memory) { return gardenWeights; } /** * Getter to get the whole array of fee weights * * @return The array of weights for the fees */ function getFeeDistributionWeights() external view override returns (uint256[] memory) { return feeDistributionWeights; } /** * Getter to get the whole array of total stats * * @return The array of stats for the fees */ function getTotalStats() external view override returns (uint256[7] memory) { return totalStats; } /** * Implements EIP-1271 */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view override returns (bytes4 magicValue) { address recovered = ECDSA.recover(_hash, _signature); return recovered == signer && recovered != address(0) ? this.isValidSignature.selector : bytes4(0); } /* ============ Internal Functions ============ */ function _bondToBABL( address _assetToBond, uint256 _amountToBond, uint256 _priceInBABL ) private view returns (uint256) { return SafeDecimalMath.normalizeAmountTokens(_assetToBond, address(BABL), _amountToBond).preciseMul( _priceInBABL.preciseMul(uint256(1e18).add(bondAssets[_assetToBond])) ); } /** * Consolidates all reserve asset fees to weth * */ function _consolidateFeesToWeth() private { address[] memory reserveAssets = controller.getReserveAssets(); for (uint256 i = 0; i < reserveAssets.length; i++) { address reserveAsset = reserveAssets[i]; uint256 balance = IERC20(reserveAsset).balanceOf(address(this)); // Trade if it's above a min amount (otherwise wait until next pump) if (reserveAsset != address(BABL) && reserveAsset != address(WETH) && balance > minAmounts[reserveAsset]) { totalStats[0] = totalStats[0].add(_trade(reserveAsset, address(WETH), balance)); } if (reserveAsset == address(WETH)) { totalStats[0] = totalStats[0].add(balance); } } emit FeesCollected(block.timestamp, IERC20(WETH).balanceOf(address(this))); } /** * Buys back BABL through the uniswap V3 BABL-ETH pool * */ function _buyback(uint256 _amount) private { // Gift 50% BABL back to garden and send 50% to the treasury uint256 bablBought = _trade(address(WETH), address(BABL), _amount); // 50% IERC20(BABL).safeTransfer(address(heartGarden), bablBought.div(2)); IERC20(BABL).safeTransfer(treasury, bablBought.div(2)); totalStats[2] = totalStats[2].add(bablBought); emit BablBuyback(block.timestamp, _amount, bablBought); } /** * Adds liquidity to the BABL-ETH pair through the hypervisor * * Note: Address of the heart needs to be whitelisted by Visor. */ function _addLiquidity(uint256 _wethBalance) private { // Buy BABL again with half to add 50/50 uint256 wethToDeposit = _wethBalance.preciseMul(5e17); uint256 bablTraded = _trade(address(WETH), address(BABL), wethToDeposit); // 50% BABL.safeApprove(address(visor), bablTraded); IERC20(WETH).safeApprove(address(visor), wethToDeposit); uint256 oldTreasuryBalance = visor.balanceOf(treasury); uint256 shares = visor.deposit(wethToDeposit, bablTraded, treasury); _require( shares == visor.balanceOf(treasury).sub(oldTreasuryBalance) && visor.balanceOf(treasury) > 0, Errors.HEART_LP_TOKENS ); totalStats[3] += _wethBalance; emit LiquidityAdded(block.timestamp, wethToDeposit, bablTraded); } /** * Invests in gardens using WETH converting it to garden reserve asset first * * @param _wethAmount Total amount of weth to invest in all gardens */ function _investInGardens(uint256 _wethAmount) private { for (uint256 i = 0; i < votedGardens.length; i++) { address reserveAsset = IGarden(votedGardens[i]).reserveAsset(); uint256 amountTraded; if (reserveAsset != address(WETH)) { amountTraded = _trade(address(WETH), reserveAsset, _wethAmount.preciseMul(gardenWeights[i])); } else { amountTraded = _wethAmount.preciseMul(gardenWeights[i]); } // Gift it to garden IERC20(reserveAsset).safeTransfer(votedGardens[i], amountTraded); emit GardenSeedInvest(block.timestamp, votedGardens[i], _wethAmount.preciseMul(gardenWeights[i])); } totalStats[4] += _wethAmount; } /** * Lends an amount of WETH converting it first to the pool asset that is the lowest (except BABL) * * @param _fromAsset Which asset to convert * @param _fromAmount Total amount of weth to lend * @param _lendAsset Address of the asset to lend */ function _lendFusePool( address _fromAsset, uint256 _fromAmount, address _lendAsset ) private { address cToken = assetToCToken[_lendAsset]; _require(cToken != address(0), Errors.HEART_INVALID_CTOKEN); uint256 assetToLendBalance = _fromAmount; // Trade to asset to lend if needed if (_fromAsset != _lendAsset) { assetToLendBalance = _trade( address(_fromAsset), _lendAsset == address(0) ? address(WETH) : _lendAsset, _fromAmount ); } if (_lendAsset == address(0)) { // Convert WETH to ETH IWETH(WETH).withdraw(_fromAmount); ICEther(cToken).mint{value: _fromAmount}(); } else { IERC20(_lendAsset).safeApprove(cToken, assetToLendBalance); ICToken(cToken).mint(assetToLendBalance); } uint256 assetToLendWethPrice = IPriceOracle(controller.priceOracle()).getPrice(_lendAsset, address(WETH)); uint256 assettoLendBalanceInWeth = assetToLendBalance.preciseMul(assetToLendWethPrice); totalStats[5] = totalStats[5].add(assettoLendBalanceInWeth); emit FuseLentAsset(block.timestamp, _lendAsset, assettoLendBalanceInWeth); } /** * Sends the weekly BABL reward to the garden (if any) */ function _sendWeeklyReward() private { if (bablRewardLeft > 0) { uint256 bablToSend = bablRewardLeft < weeklyRewardAmount ? bablRewardLeft : weeklyRewardAmount; uint256 currentBalance = IERC20(BABL).balanceOf(address(this)); bablToSend = currentBalance < bablToSend ? currentBalance : bablToSend; IERC20(BABL).safeTransfer(address(heartGarden), bablToSend); bablRewardLeft = bablRewardLeft.sub(bablToSend); emit BABLRewardSent(block.timestamp, bablToSend); totalStats[6] = totalStats[6].add(bablToSend); } } /** * Trades _tokenIn to _tokenOut using Uniswap V3 * * @param _tokenIn Token that is sold * @param _tokenOut Token that is purchased * @param _amount Amount of tokenin to sell */ function _trade( address _tokenIn, address _tokenOut, uint256 _amount ) private returns (uint256) { if (_tokenIn == _tokenOut) { return _amount; } // Uses on chain oracle for all internal strategy operations to avoid attacks uint256 pricePerTokenUnit = IPriceOracle(controller.priceOracle()).getPrice(_tokenIn, _tokenOut); _require(pricePerTokenUnit != 0, Errors.NO_PRICE_FOR_TRADE); // minAmount must have receive token decimals uint256 exactAmount = SafeDecimalMath.normalizeAmountTokens(_tokenIn, _tokenOut, _amount.preciseMul(pricePerTokenUnit)); uint256 minAmountOut = exactAmount.sub(exactAmount.preciseMul(tradeSlippage)); return _trade(_tokenIn, _tokenOut, _amount, minAmountOut, address(0)); } /** * Trades _tokenIn to _tokenOut using Uniswap V3 * * @param _tokenIn Token that is sold * @param _tokenOut Token that is purchased * @param _amount Amount of tokenin to sell * @param _minAmountOut Min amount of tokens out to recive * @param _hopToken Hop token to use for UniV3 trade */ function _trade( address _tokenIn, address _tokenOut, uint256 _amount, uint256 _minAmountOut, address _hopToken ) private returns (uint256) { ISwapRouter swapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Approve the router to spend token in. TransferHelper.safeApprove(_tokenIn, address(swapRouter), _amount); bytes memory path; if ( (_tokenIn == address(FRAX) && _tokenOut != address(DAI)) || (_tokenOut == address(FRAX) && _tokenIn != address(DAI)) ) { _hopToken = address(DAI); } else { if ( (_tokenIn == address(FEI) && _tokenOut != address(USDC)) || (_tokenOut == address(FEI) && _tokenIn != address(USDC)) ) { _hopToken = address(USDC); } } if (_hopToken != address(0)) { uint24 fee0 = _getUniswapPoolFeeWithHighestLiquidity(_tokenIn, _hopToken); uint24 fee1 = _getUniswapPoolFeeWithHighestLiquidity(_tokenOut, _hopToken); // Have to use WETH for BABL because the most liquid pari is WETH/BABL if (_tokenOut == address(BABL) && _hopToken != address(WETH)) { path = abi.encodePacked( _tokenIn, fee0, _hopToken, fee1, address(WETH), _getUniswapPoolFeeWithHighestLiquidity(address(WETH), _tokenOut), _tokenOut ); } else { path = abi.encodePacked(_tokenIn, fee0, _hopToken, fee1, _tokenOut); } } else { uint24 fee = _getUniswapPoolFeeWithHighestLiquidity(_tokenIn, _tokenOut); path = abi.encodePacked(_tokenIn, fee, _tokenOut); } ISwapRouter.ExactInputParams memory params = ISwapRouter.ExactInputParams(path, address(this), block.timestamp, _amount, _minAmountOut); return swapRouter.exactInput(params); } /** * Returns the FEE of the highest liquidity pool in univ3 for this pair * @param sendToken Token that is sold * @param receiveToken Token that is purchased */ function _getUniswapPoolFeeWithHighestLiquidity(address sendToken, address receiveToken) private view returns (uint24) { IUniswapV3Pool poolLow = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_LOW)); IUniswapV3Pool poolMedium = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_MEDIUM)); IUniswapV3Pool poolHigh = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_HIGH)); uint128 liquidityLow = address(poolLow) != address(0) ? poolLow.liquidity() : 0; uint128 liquidityMedium = address(poolMedium) != address(0) ? poolMedium.liquidity() : 0; uint128 liquidityHigh = address(poolHigh) != address(0) ? poolHigh.liquidity() : 0; if (liquidityLow >= liquidityMedium && liquidityLow >= liquidityHigh) { return FEE_LOW; } if (liquidityMedium >= liquidityLow && liquidityMedium >= liquidityHigh) { return FEE_MEDIUM; } return FEE_HIGH; } } contract HeartV5 is Heart { constructor(IBabController _controller, IGovernor _governor) Heart(_controller, _governor) {} } // 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.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IHypervisor { // @param deposit0 Amount of token0 transfered from sender to Hypervisor // @param deposit1 Amount of token0 transfered from sender to Hypervisor // @param to Address to which liquidity tokens are minted // @return shares Quantity of liquidity tokens minted as a result of deposit function deposit( uint256 deposit0, uint256 deposit1, address to ) external returns (uint256); // @param shares Number of liquidity tokens to redeem as pool assets // @param to Address to which redeemed pool assets are sent // @param from Address from which liquidity tokens are sent // @return amount0 Amount of token0 redeemed by the submitted liquidity tokens // @return amount1 Amount of token1 redeemed by the submitted liquidity tokens function withdraw( uint256 shares, address to, address from ) external returns (uint256, uint256); function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, address _feeRecipient, int256 swapQuantity ) external; function addBaseLiquidity(uint256 amount0, uint256 amount1) external; function addLimitLiquidity(uint256 amount0, uint256 amount1) external; function pullLiquidity(uint256 shares) external returns ( uint256 base0, uint256 base1, uint256 limit0, uint256 limit1 ); function token0() external view returns (IERC20); function token1() external view returns (IERC20); function pool() external view returns (address); function balanceOf(address) external view returns (uint256); function approve(address, uint256) external returns (bool); function transferFrom( address, address, uint256 ) external returns (bool); function transfer(address, uint256) external returns (bool); function getTotalAmounts() external view returns (uint256 total0, uint256 total1); function pendingFees() external returns (uint256 fees0, uint256 fees1); function totalSupply() external view returns (uint256); function setMaxTotalSupply(uint256 _maxTotalSupply) external; function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external; function appendList(address[] memory listed) external; function toggleWhitelist() external; function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @title IBabController * @author Babylon Finance * * Interface for interacting with BabController */ interface IBabController { /* ============ Functions ============ */ function createGarden( address _reserveAsset, string memory _name, string memory _symbol, string memory _tokenURI, uint256 _seed, uint256[] calldata _gardenParams, uint256 _initialContribution, bool[] memory _publicGardenStrategistsStewards, uint256[] memory _profitSharing ) external payable returns (address); function removeGarden(address _garden) external; function addReserveAsset(address _reserveAsset) external; function removeReserveAsset(address _reserveAsset) external; function updateProtocolWantedAsset(address _wantedAsset, bool _wanted) external; function updateGardenAffiliateRate(address _garden, uint256 _affiliateRate) external; function addAffiliateReward(address _user, uint256 _reserveAmount) external; function claimRewards() external; function editPriceOracle(address _priceOracle) external; function editMardukGate(address _mardukGate) external; function editGardenValuer(address _gardenValuer) external; function editTreasury(address _newTreasury) external; function editHeart(address _newHeart) external; function editRewardsDistributor(address _rewardsDistributor) external; function editGardenFactory(address _newGardenFactory) external; function editGardenNFT(address _newGardenNFT) external; function editCurveMetaRegistry(address _curveMetaRegistry) external; function editStrategyNFT(address _newStrategyNFT) external; function editStrategyFactory(address _newStrategyFactory) external; function setOperation(uint8 _kind, address _operation) external; function setMasterSwapper(address _newMasterSwapper) external; function addKeeper(address _keeper) external; function addKeepers(address[] memory _keepers) external; function removeKeeper(address _keeper) external; function enableGardenTokensTransfers() external; function editLiquidityReserve(address _reserve, uint256 _minRiskyPairLiquidityEth) external; function gardenCreationIsOpen() external view returns (bool); function owner() external view returns (address); function EMERGENCY_OWNER() external view returns (address); function guardianGlobalPaused() external view returns (bool); function guardianPaused(address _address) external view returns (bool); function setPauseGuardian(address _guardian) external; function setGlobalPause(bool _state) external returns (bool); function setSomePause(address[] memory _address, bool _state) external returns (bool); function isPaused(address _contract) external view returns (bool); function priceOracle() external view returns (address); function gardenValuer() external view returns (address); function heart() external view returns (address); function gardenNFT() external view returns (address); function strategyNFT() external view returns (address); function curveMetaRegistry() external view returns (address); function rewardsDistributor() external view returns (address); function gardenFactory() external view returns (address); function treasury() external view returns (address); function ishtarGate() external view returns (address); function mardukGate() external view returns (address); function strategyFactory() external view returns (address); function masterSwapper() external view returns (address); function gardenTokensTransfersEnabled() external view returns (bool); function bablMiningProgramEnabled() external view returns (bool); function allowPublicGardens() external view returns (bool); function enabledOperations(uint256 _kind) external view returns (address); function getGardens() external view returns (address[] memory); function getReserveAssets() external view returns (address[] memory); function getOperations() external view returns (address[20] memory); function isGarden(address _garden) external view returns (bool); function protocolWantedAssets(address _wantedAsset) external view returns (bool); function gardenAffiliateRates(address _wantedAsset) external view returns (uint256); function affiliateRewards(address _user) external view returns (uint256); function isValidReserveAsset(address _reserveAsset) external view returns (bool); function isValidKeeper(address _keeper) external view returns (bool); function isSystemContract(address _contractAddress) external view returns (bool); function protocolPerformanceFee() external view returns (uint256); function protocolManagementFee() external view returns (uint256); function minLiquidityPerReserve(address _reserve) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (governance/IGovernor.sol) pragma solidity ^0.7.6; pragma abicoder v2; /** * @dev Interface of the {Governor} core. * * _Available since v4.3._ */ abstract contract IGovernor { enum ProposalState {Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed} /** * @dev Emitted when a proposal is created. */ event ProposalCreated( uint256 proposalId, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /** * @dev Emitted when a proposal is canceled. */ event ProposalCanceled(uint256 proposalId); /** * @dev Emitted when a proposal is executed. */ event ProposalExecuted(uint256 proposalId); /** * @dev Emitted when a vote is cast. * * Note: `support` values should be seen as buckets. There interpretation depends on the voting module used. */ event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason); /** * @notice module:core * @dev Name of the governor instance (used in building the ERC712 domain separator). */ function name() public view virtual returns (string memory); /** * @notice module:core * @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1" */ function version() public view virtual returns (string memory); function proposals(uint256 _proposalId) public view virtual returns ( uint256, address, uint256, uint256, uint256, uint256, uint256, uint256, bool, bool ); /** * @notice module:voting * @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to * be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of * key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`. * * There are 2 standard keys: `support` and `quorum`. * * - `support=bravo` refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in `GovernorBravo`. * - `quorum=bravo` means that only For votes are counted towards quorum. * - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum. * * NOTE: The string can be decoded by the standard * https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] * JavaScript class. */ // solhint-disable-next-line func-name-mixedcase function COUNTING_MODE() public pure virtual returns (string memory); /** * @notice module:core * @dev Hashing function used to (re)build the proposal id from the proposal details.. */ function hashProposal( address[] calldata targets, uint256[] calldata values, bytes[] calldata calldatas, bytes32 descriptionHash ) public pure virtual returns (uint256); /** * @notice module:core * @dev Current state of a proposal, following Compound's convention */ function state(uint256 proposalId) public view virtual returns (ProposalState); /** * @notice module:core * @dev Block number used to retrieve user's votes and quorum. As per Compound's Comp and OpenZeppelin's * ERC20Votes, the snapshot is performed at the end of this block. Hence, voting for this proposal starts at the * beginning of the following block. */ function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:core * @dev Block number at which votes close. Votes close at the end of this block, so it is possible to cast a vote * during this block. */ function proposalDeadline(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:user-config * @dev Delay, in number of block, between the proposal is created and the vote starts. This can be increassed to * leave time for users to buy voting power, of delegate it, before the voting of a proposal starts. */ function votingDelay() public view virtual returns (uint256); /** * @notice module:user-config * @dev Delay, in number of blocks, between the vote start and vote ends. * * NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting * duration compared to the voting delay. */ function votingPeriod() public view virtual returns (uint256); /** * @notice module:user-config * @dev Minimum number of cast voted required for a proposal to be successful. * * Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the * quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}). */ function quorum(uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:reputation * @dev Voting power of an `account` at a specific `blockNumber`. * * Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or * multiple), {ERC20Votes} tokens. */ function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:voting * @dev Returns weither `account` has cast a vote on `proposalId`. */ function hasVoted(uint256 proposalId, address account) public view virtual returns (bool); /** * @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends * {IGovernor-votingPeriod} blocks after the voting starts. * * Emits a {ProposalCreated} event. */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public virtual returns (uint256 proposalId); /** * @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the * deadline to be reached. * * Emits a {ProposalExecuted} event. * * Note: some module can modify the requirements for execution, for example by adding an additional timelock. */ function execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public payable virtual returns (uint256 proposalId); /** * @dev Cast a vote * * Emits a {VoteCast} event. */ function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance); /** * @dev Cast a vote with a reason * * Emits a {VoteCast} event. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public virtual returns (uint256 balance); /** * @dev Cast a vote using the user cryptographic signature. * * Emits a {VoteCast} event. */ function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual returns (uint256 balance); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {IERC1271} from '../interfaces/IERC1271.sol'; import {IBabController} from './IBabController.sol'; /** * @title IStrategyGarden * * Interface for functions of the garden */ interface IStrategyGarden { /* ============ Write ============ */ function finalizeStrategy( uint256 _profits, int256 _returns, uint256 _burningAmount ) external; function allocateCapitalToStrategy(uint256 _capital) external; function expireCandidateStrategy(address _strategy) external; function addStrategy( string memory _name, string memory _symbol, uint256[] calldata _stratParams, uint8[] calldata _opTypes, address[] calldata _opIntegrations, bytes calldata _opEncodedDatas ) external; function updateStrategyRewards( address _strategy, uint256 _newTotalAmount, uint256 _newCapitalReturned ) external; function payKeeper(address payable _keeper, uint256 _fee) external; } /** * @title IAdminGarden * * Interface for amdin functions of the Garden */ interface IAdminGarden { /* ============ Write ============ */ function initialize( address _reserveAsset, IBabController _controller, address _creator, string memory _name, string memory _symbol, uint256[] calldata _gardenParams, uint256 _initialContribution, bool[] memory _publicGardenStrategistsStewards ) external payable; function makeGardenPublic() external; function transferCreatorRights(address _newCreator, uint8 _index) external; function addExtraCreators(address[4] memory _newCreators) external; function setPublicRights(bool _publicStrategist, bool _publicStewards) external; function delegateVotes(address _token, address _address) external; function updateCreators(address _newCreator, address[4] memory _newCreators) external; function updateGardenParams(uint256[12] memory _newParams) external; function verifyGarden(uint256 _verifiedCategory) external; function resetHardlock(uint256 _hardlockStartsAt) external; } /** * @title IGarden * * Interface for operating with a Garden. */ interface ICoreGarden { /* ============ Constructor ============ */ /* ============ View ============ */ function privateGarden() external view returns (bool); function publicStrategists() external view returns (bool); function publicStewards() external view returns (bool); function controller() external view returns (IBabController); function creator() external view returns (address); function isGardenStrategy(address _strategy) external view returns (bool); function getContributor(address _contributor) external view returns ( uint256 lastDepositAt, uint256 initialDepositAt, uint256 claimedAt, uint256 claimedBABL, uint256 claimedRewards, uint256 withdrawnSince, uint256 totalDeposits, uint256 nonce, uint256 lockedBalance ); function reserveAsset() external view returns (address); function verifiedCategory() external view returns (uint256); function canMintNftAfter() external view returns (uint256); function hardlockStartsAt() external view returns (uint256); function totalContributors() external view returns (uint256); function gardenInitializedAt() external view returns (uint256); function minContribution() external view returns (uint256); function depositHardlock() external view returns (uint256); function minLiquidityAsset() external view returns (uint256); function minStrategyDuration() external view returns (uint256); function maxStrategyDuration() external view returns (uint256); function reserveAssetRewardsSetAside() external view returns (uint256); function absoluteReturns() external view returns (int256); function totalStake() external view returns (uint256); function minVotesQuorum() external view returns (uint256); function minVoters() external view returns (uint256); function maxDepositLimit() external view returns (uint256); function strategyCooldownPeriod() external view returns (uint256); function getStrategies() external view returns (address[] memory); function extraCreators(uint256 index) external view returns (address); function getFinalizedStrategies() external view returns (address[] memory); function strategyMapping(address _strategy) external view returns (bool); function keeperDebt() external view returns (uint256); function totalKeeperFees() external view returns (uint256); function lastPricePerShare() external view returns (uint256); function lastPricePerShareTS() external view returns (uint256); function pricePerShareDecayRate() external view returns (uint256); function pricePerShareDelta() external view returns (uint256); /* ============ Write ============ */ function deposit( uint256 _amountIn, uint256 _minAmountOut, address _to, address _referrer ) external payable; function depositBySig( uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, address _to, uint256 _pricePerShare, uint256 _fee, address _signer, address _referrer, bytes memory signature ) external; function withdraw( uint256 _amountIn, uint256 _minAmountOut, address payable _to, bool _withPenalty, address _unwindStrategy ) external; function withdrawBySig( uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, bool _withPenalty, address _unwindStrategy, uint256 _pricePerShare, uint256 _strategyNAV, uint256 _fee, address _signer, bytes memory signature ) external; function claimReturns(address[] calldata _finalizedStrategies) external; function claimAndStakeReturns(uint256 _minAmountOut, address[] calldata _finalizedStrategies) external; function claimRewardsBySig( uint256 _babl, uint256 _profits, uint256 _nonce, uint256 _maxFee, uint256 _fee, address signer, bytes memory signature ) external; function claimAndStakeRewardsBySig( uint256 _babl, uint256 _profits, uint256 _minAmountOut, uint256 _nonce, uint256 _nonceHeart, uint256 _maxFee, uint256 _pricePerShare, uint256 _fee, address _signer, bytes memory _signature ) external; function stakeBySig( uint256 _amountIn, uint256 _profits, uint256 _minAmountOut, uint256 _nonce, uint256 _nonceHeart, uint256 _maxFee, address _to, uint256 _pricePerShare, address _signer, bytes memory _signature ) external; function claimNFT() external; } interface IERC20Metadata { function name() external view returns (string memory); } interface IGarden is ICoreGarden, IAdminGarden, IStrategyGarden, IERC20, IERC20Metadata, IERC1271 { struct Contributor { uint256 lastDepositAt; uint256 initialDepositAt; uint256 claimedAt; uint256 claimedBABL; uint256 claimedRewards; uint256 withdrawnSince; uint256 totalDeposits; uint256 nonce; uint256 lockedBalance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IGarden} from './IGarden.sol'; /** * @title IHeart * @author Babylon Finance * * Interface for interacting with the Heart */ interface IHeart { // View functions function getVotedGardens() external view returns (address[] memory); function heartGarden() external view returns (IGarden); function getGardenWeights() external view returns (uint256[] memory); function minAmounts(address _reserve) external view returns (uint256); function assetToCToken(address _asset) external view returns (address); function bondAssets(address _asset) external view returns (uint256); function assetToLend() external view returns (address); function assetForPurchases() external view returns (address); function lastPumpAt() external view returns (uint256); function lastVotesAt() external view returns (uint256); function tradeSlippage() external view returns (uint256); function weeklyRewardAmount() external view returns (uint256); function bablRewardLeft() external view returns (uint256); function getFeeDistributionWeights() external view returns (uint256[] memory); function getTotalStats() external view returns (uint256[7] memory); function votedGardens(uint256 _index) external view returns (address); function gardenWeights(uint256 _index) external view returns (uint256); function feeDistributionWeights(uint256 _index) external view returns (uint256); function totalStats(uint256 _index) external view returns (uint256); // Non-view function pump() external; function voteProposal(uint256 _proposalId, bool _isApprove) external; function resolveGardenVotesAndPump(address[] memory _gardens, uint256[] memory _weights) external; function resolveGardenVotes(address[] memory _gardens, uint256[] memory _weights) external; function updateMarkets() external; function setHeartGardenAddress(address _heartGarden) external; function updateFeeWeights(uint256[] calldata _feeWeights) external; function updateAssetToLend(address _assetToLend) external; function updateAssetToPurchase(address _purchaseAsset) external; function updateBond(address _assetToBond, uint256 _bondDiscount) external; function lendFusePool(address _assetToLend, uint256 _lendAmount) external; function borrowFusePool(address _assetToBorrow, uint256 _borrowAmount) external; function repayFusePool(address _borrowedAsset, uint256 _amountToRepay) external; function protectBABL( uint256 _bablPriceProtectionAt, uint256 _bablPrice, uint256 _pricePurchasingAsset, uint256 _slippage, address _hopToken ) external; function trade( address _fromAsset, address _toAsset, uint256 _fromAmount, uint256 _minAmount ) external; function sellWantedAssetToHeart(address _assetToSell, uint256 _amountToSell) external; function addReward(uint256 _bablAmount, uint256 _weeklyRate) external; function setMinTradeAmount(address _asset, uint256 _minAmount) external; function setTradeSlippage(uint256 _tradeSlippage) external; function bondAsset( address _assetToBond, uint256 _amountToBond, uint256 _minAmountOut, address _referrer ) external; function bondAssetBySig( address _assetToBond, uint256 _amountToBond, uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, uint256 _priceInBABL, uint256 _pricePerShare, uint256 _fee, address _contributor, address _referrer, bytes memory _signature ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface ICToken is IERC20 { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function accrueInterest() external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function totalBorrows() external view returns (uint256); function underlying() external view returns (address); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function repayBorrowBehalf(address borrower, uint256 amount) external payable returns (uint256); function borrowBalanceCurrent(address account) external view returns (uint256); function supplyRatePerBlock() external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; interface ICEther { function mint() external payable; function borrow(uint256 borrowAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function repayBorrow() external payable; function getCash() external view returns (uint256); function repayBorrowBehalf(address borrower) external payable; function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function exchangeRateCurrent() external returns (uint256); function supplyRatePerBlock() external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; interface IComptroller { /** * @notice Marker function used for light validation when updating the comptroller of a market * @dev Implementations should simply return true. * @return true */ function isComptroller() external view returns (bool); function markets(address _cToken) external view returns (bool, uint256); function getRewardsDistributors() external view returns (address[] memory); /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); function getAllMarkets() external view returns (address[] memory); function _borrowGuardianPaused() external view returns (bool); function borrowGuardianPaused(address _asset) external view returns (bool); function borrowCaps(address _asset) external view returns (uint256); function compAccrued(address holder) external view returns (uint256); /*** Policy Hooks ***/ function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); function getAssetsIn(address account) external view returns (address[] memory); 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); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {ITokenIdentifier} from './ITokenIdentifier.sol'; /** * @title IPriceOracle * @author Babylon Finance * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function getPriceNAV(address _assetOne, address _assetTwo) external view returns (uint256); function updateReserves(address[] memory list) external; function updateMaxTwapDeviation(int24 _maxTwapDeviation) external; function updateTokenIdentifier(ITokenIdentifier _tokenIdentifier) external; function getCompoundExchangeRate(address _asset, address _finalAsset) external view returns (uint256); function getCreamExchangeRate(address _asset, address _finalAsset) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {ITradeIntegration} from './ITradeIntegration.sol'; /** * @title IIshtarGate * @author Babylon Finance * * Interface for interacting with the Gate Guestlist NFT */ interface IMasterSwapper is ITradeIntegration { /* ============ Functions ============ */ function isTradeIntegration(address _integration) external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IVoteToken { function delegate(address delegatee) external; function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external; function getCurrentVotes(address account) external view returns (uint96); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); function getMyDelegatee() external view returns (address); function getDelegatee(address account) external view returns (address); function getCheckpoints(address account, uint32 id) external view returns (uint32 fromBlock, uint96 votes); function getNumberOfCheckpoints(address account) external view returns (uint32); } interface IVoteTokenWithERC20 is IVoteToken, IERC20 {} // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {SignedSafeMath} from '@openzeppelin/contracts/math/SignedSafeMath.sol'; import {LowGasSafeMath} from './LowGasSafeMath.sol'; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using LowGasSafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 internal constant PRECISE_UNIT = 10**18; int256 internal constant PRECISE_UNIT_INT = 10**18; // Max unsigned integer value uint256 internal constant MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 internal constant MAX_INT_256 = type(int256).max; int256 internal constant MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function decimals() internal pure returns (uint256) { return 18; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, 'Cant divide by 0'); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, 'Cant divide by 0'); require(a != MIN_INT_256 || b != -1, 'Invalid input'); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower(uint256 a, uint256 pow) internal pure returns (uint256) { require(a > 0, 'Value must be positive'); uint256 result = 1; for (uint256 i = 0; i < pow; i++) { uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {LowGasSafeMath} from '../lib/LowGasSafeMath.sol'; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; library SafeDecimalMath { using LowGasSafeMath for uint256; /* Number of decimal places in the representations. */ uint8 internal constant decimals = 18; /* The number representing 1.0. */ uint256 internal constant UNIT = 10**uint256(decimals); /** * @return Provides an interface to UNIT. */ function unit() internal pure returns (uint256) { return UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint256 quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { uint256 resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, UNIT); } /** * Normalizing amount decimals between tokens * @param _from ERC20 asset address * @param _to ERC20 asset address * @param _amount Value _to normalize (e.g. capital) */ function normalizeAmountTokens( address _from, address _to, uint256 _amount ) internal view returns (uint256) { uint256 fromDecimals = _isETH(_from) ? 18 : ERC20(_from).decimals(); uint256 toDecimals = _isETH(_to) ? 18 : ERC20(_to).decimals(); if (fromDecimals == toDecimals) { return _amount; } if (toDecimals > fromDecimals) { return _amount.mul(10**(toDecimals - (fromDecimals))); } return _amount.div(10**(fromDecimals - (toDecimals))); } function _isETH(address _address) internal pure returns (bool) { return _address == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE || _address == address(0); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } /** * @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; } } // SPDX-License-Identifier: Apache-2.0 /* Original version by Synthetix.io https://docs.synthetix.io/contracts/source/libraries/safedecimalmath Adapted by Babylon Finance. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; // solhint-disable /** * @notice Forked from https://github.com/balancer-labs/balancer-core-v2/blob/master/contracts/lib/helpers/BalancerErrors.sol * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAB#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAB#" part is a known constant // (0x42414223): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414223000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Max deposit limit needs to be under the limit uint256 internal constant MAX_DEPOSIT_LIMIT = 0; // Creator needs to deposit uint256 internal constant MIN_CONTRIBUTION = 1; // Min Garden token supply >= 0 uint256 internal constant MIN_TOKEN_SUPPLY = 2; // Deposit hardlock needs to be at least 1 block uint256 internal constant DEPOSIT_HARDLOCK = 3; // Needs to be at least the minimum uint256 internal constant MIN_LIQUIDITY = 4; // _reserveAssetQuantity is not equal to msg.value uint256 internal constant MSG_VALUE_DO_NOT_MATCH = 5; // Withdrawal amount has to be equal or less than msg.sender balance uint256 internal constant MSG_SENDER_TOKENS_DO_NOT_MATCH = 6; // Tokens are staked uint256 internal constant TOKENS_STAKED = 7; // Balance too low uint256 internal constant BALANCE_TOO_LOW = 8; // msg.sender doesn't have enough tokens uint256 internal constant MSG_SENDER_TOKENS_TOO_LOW = 9; // There is an open redemption window already uint256 internal constant REDEMPTION_OPENED_ALREADY = 10; // Cannot request twice in the same window uint256 internal constant ALREADY_REQUESTED = 11; // Rewards and profits already claimed uint256 internal constant ALREADY_CLAIMED = 12; // Value have to be greater than zero uint256 internal constant GREATER_THAN_ZERO = 13; // Must be reserve asset uint256 internal constant MUST_BE_RESERVE_ASSET = 14; // Only contributors allowed uint256 internal constant ONLY_CONTRIBUTOR = 15; // Only controller allowed uint256 internal constant ONLY_CONTROLLER = 16; // Only creator allowed uint256 internal constant ONLY_CREATOR = 17; // Only keeper allowed uint256 internal constant ONLY_KEEPER = 18; // Fee is too high uint256 internal constant FEE_TOO_HIGH = 19; // Only strategy allowed uint256 internal constant ONLY_STRATEGY = 20; // Only active allowed uint256 internal constant ONLY_ACTIVE = 21; // Only inactive allowed uint256 internal constant ONLY_INACTIVE = 22; // Address should be not zero address uint256 internal constant ADDRESS_IS_ZERO = 23; // Not within range uint256 internal constant NOT_IN_RANGE = 24; // Value is too low uint256 internal constant VALUE_TOO_LOW = 25; // Value is too high uint256 internal constant VALUE_TOO_HIGH = 26; // Only strategy or protocol allowed uint256 internal constant ONLY_STRATEGY_OR_CONTROLLER = 27; // Normal withdraw possible uint256 internal constant NORMAL_WITHDRAWAL_POSSIBLE = 28; // User does not have permissions to join garden uint256 internal constant USER_CANNOT_JOIN = 29; // User does not have permissions to add strategies in garden uint256 internal constant USER_CANNOT_ADD_STRATEGIES = 30; // Only Protocol or garden uint256 internal constant ONLY_PROTOCOL_OR_GARDEN = 31; // Only Strategist uint256 internal constant ONLY_STRATEGIST = 32; // Only Integration uint256 internal constant ONLY_INTEGRATION = 33; // Only garden and data not set uint256 internal constant ONLY_GARDEN_AND_DATA_NOT_SET = 34; // Only active garden uint256 internal constant ONLY_ACTIVE_GARDEN = 35; // Contract is not a garden uint256 internal constant NOT_A_GARDEN = 36; // Not enough tokens uint256 internal constant STRATEGIST_TOKENS_TOO_LOW = 37; // Stake is too low uint256 internal constant STAKE_HAS_TO_AT_LEAST_ONE = 38; // Duration must be in range uint256 internal constant DURATION_MUST_BE_IN_RANGE = 39; // Max Capital Requested uint256 internal constant MAX_CAPITAL_REQUESTED = 41; // Votes are already resolved uint256 internal constant VOTES_ALREADY_RESOLVED = 42; // Voting window is closed uint256 internal constant VOTING_WINDOW_IS_OVER = 43; // Strategy needs to be active uint256 internal constant STRATEGY_NEEDS_TO_BE_ACTIVE = 44; // Max capital reached uint256 internal constant MAX_CAPITAL_REACHED = 45; // Capital is less then rebalance uint256 internal constant CAPITAL_IS_LESS_THAN_REBALANCE = 46; // Strategy is in cooldown period uint256 internal constant STRATEGY_IN_COOLDOWN = 47; // Strategy is not executed uint256 internal constant STRATEGY_IS_NOT_EXECUTED = 48; // Strategy is not over yet uint256 internal constant STRATEGY_IS_NOT_OVER_YET = 49; // Strategy is already finalized uint256 internal constant STRATEGY_IS_ALREADY_FINALIZED = 50; // No capital to unwind uint256 internal constant STRATEGY_NO_CAPITAL_TO_UNWIND = 51; // Strategy needs to be inactive uint256 internal constant STRATEGY_NEEDS_TO_BE_INACTIVE = 52; // Duration needs to be less uint256 internal constant DURATION_NEEDS_TO_BE_LESS = 53; // Can't sweep reserve asset uint256 internal constant CANNOT_SWEEP_RESERVE_ASSET = 54; // Voting window is opened uint256 internal constant VOTING_WINDOW_IS_OPENED = 55; // Strategy is executed uint256 internal constant STRATEGY_IS_EXECUTED = 56; // Min Rebalance Capital uint256 internal constant MIN_REBALANCE_CAPITAL = 57; // Not a valid strategy NFT uint256 internal constant NOT_STRATEGY_NFT = 58; // Garden Transfers Disabled uint256 internal constant GARDEN_TRANSFERS_DISABLED = 59; // Tokens are hardlocked uint256 internal constant TOKENS_HARDLOCKED = 60; // Max contributors reached uint256 internal constant MAX_CONTRIBUTORS = 61; // BABL Transfers Disabled uint256 internal constant BABL_TRANSFERS_DISABLED = 62; // Strategy duration range error uint256 internal constant DURATION_RANGE = 63; // Checks the min amount of voters uint256 internal constant MIN_VOTERS_CHECK = 64; // Ge contributor power error uint256 internal constant CONTRIBUTOR_POWER_CHECK_WINDOW = 65; // Not enough reserve set aside uint256 internal constant NOT_ENOUGH_RESERVE = 66; // Garden is already public uint256 internal constant GARDEN_ALREADY_PUBLIC = 67; // Withdrawal with penalty uint256 internal constant WITHDRAWAL_WITH_PENALTY = 68; // Withdrawal with penalty uint256 internal constant ONLY_MINING_ACTIVE = 69; // Overflow in supply uint256 internal constant OVERFLOW_IN_SUPPLY = 70; // Overflow in power uint256 internal constant OVERFLOW_IN_POWER = 71; // Not a system contract uint256 internal constant NOT_A_SYSTEM_CONTRACT = 72; // Strategy vs Garden mismatch uint256 internal constant STRATEGY_GARDEN_MISMATCH = 73; // Minimum quarters is 1 uint256 internal constant QUARTERS_MIN_1 = 74; // Too many strategy operations uint256 internal constant TOO_MANY_OPS = 75; // Only operations uint256 internal constant ONLY_OPERATION = 76; // Strat params wrong length uint256 internal constant STRAT_PARAMS_LENGTH = 77; // Garden params wrong length uint256 internal constant GARDEN_PARAMS_LENGTH = 78; // Token names too long uint256 internal constant NAME_TOO_LONG = 79; // Contributor power overflows over garden power uint256 internal constant CONTRIBUTOR_POWER_OVERFLOW = 80; // Contributor power window out of bounds uint256 internal constant CONTRIBUTOR_POWER_CHECK_DEPOSITS = 81; // Contributor power window out of bounds uint256 internal constant NO_REWARDS_TO_CLAIM = 82; // Pause guardian paused this operation uint256 internal constant ONLY_UNPAUSED = 83; // Reentrant intent uint256 internal constant REENTRANT_CALL = 84; // Reserve asset not supported uint256 internal constant RESERVE_ASSET_NOT_SUPPORTED = 85; // Withdrawal/Deposit check min amount received uint256 internal constant RECEIVE_MIN_AMOUNT = 86; // Total Votes has to be positive uint256 internal constant TOTAL_VOTES_HAVE_TO_BE_POSITIVE = 87; // Signer has to be valid uint256 internal constant INVALID_SIGNER = 88; // Nonce has to be valid uint256 internal constant INVALID_NONCE = 89; // Garden is not public uint256 internal constant GARDEN_IS_NOT_PUBLIC = 90; // Setting max contributors uint256 internal constant MAX_CONTRIBUTORS_SET = 91; // Profit sharing mismatch for customized gardens uint256 internal constant PROFIT_SHARING_MISMATCH = 92; // Max allocation percentage uint256 internal constant MAX_STRATEGY_ALLOCATION_PERCENTAGE = 93; // new creator must not exist uint256 internal constant NEW_CREATOR_MUST_NOT_EXIST = 94; // only first creator can add uint256 internal constant ONLY_FIRST_CREATOR_CAN_ADD = 95; // invalid address uint256 internal constant INVALID_ADDRESS = 96; // creator can only renounce in some circumstances uint256 internal constant CREATOR_CANNOT_RENOUNCE = 97; // no price for trade uint256 internal constant NO_PRICE_FOR_TRADE = 98; // Max capital requested uint256 internal constant ZERO_CAPITAL_REQUESTED = 99; // Unwind capital above the limit uint256 internal constant INVALID_CAPITAL_TO_UNWIND = 100; // Mining % sharing does not match uint256 internal constant INVALID_MINING_VALUES = 101; // Max trade slippage percentage uint256 internal constant MAX_TRADE_SLIPPAGE_PERCENTAGE = 102; // Max gas fee percentage uint256 internal constant MAX_GAS_FEE_PERCENTAGE = 103; // Mismatch between voters and votes uint256 internal constant INVALID_VOTES_LENGTH = 104; // Only Rewards Distributor uint256 internal constant ONLY_RD = 105; // Fee is too LOW uint256 internal constant FEE_TOO_LOW = 106; // Only governance or emergency uint256 internal constant ONLY_GOVERNANCE_OR_EMERGENCY = 107; // Strategy invalid reserve asset amount uint256 internal constant INVALID_RESERVE_AMOUNT = 108; // Heart only pumps once a week uint256 internal constant HEART_ALREADY_PUMPED = 109; // Heart needs garden votes to pump uint256 internal constant HEART_VOTES_MISSING = 110; // Not enough fees for heart uint256 internal constant HEART_MINIMUM_FEES = 111; // Invalid heart votes length uint256 internal constant HEART_VOTES_LENGTH = 112; // Heart LP tokens not received uint256 internal constant HEART_LP_TOKENS = 113; // Heart invalid asset to lend uint256 internal constant HEART_ASSET_LEND_INVALID = 114; // Heart garden not set uint256 internal constant HEART_GARDEN_NOT_SET = 115; // Heart asset to lend is the same uint256 internal constant HEART_ASSET_LEND_SAME = 116; // Heart invalid ctoken uint256 internal constant HEART_INVALID_CTOKEN = 117; // Price per share is wrong uint256 internal constant PRICE_PER_SHARE_WRONG = 118; // Heart asset to purchase is same uint256 internal constant HEART_ASSET_PURCHASE_INVALID = 119; // Reset hardlock bigger than timestamp uint256 internal constant RESET_HARDLOCK_INVALID = 120; // Invalid referrer uint256 internal constant INVALID_REFERRER = 121; // Only Heart Garden uint256 internal constant ONLY_HEART_GARDEN = 122; // Max BABL Cap to claim by sig uint256 internal constant MAX_BABL_CAP_REACHED = 123; // Not enough BABL uint256 internal constant NOT_ENOUGH_BABL = 124; // Claim garden NFT uint256 internal constant CLAIM_GARDEN_NFT = 125; // Not enough collateral uint256 internal constant NOT_ENOUGH_COLLATERAL = 126; // Amount too low uint256 internal constant AMOUNT_TOO_LOW = 127; // Amount too high uint256 internal constant AMOUNT_TOO_HIGH = 128; // Not enough to repay debt uint256 internal constant SLIPPAGE_TOO_HIH = 129; // Invalid amount uint256 internal constant INVALID_AMOUNT = 130; // Not enough BABL uint256 internal constant NOT_ENOUGH_AMOUNT = 131; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IBabController} from '../interfaces/IBabController.sol'; library ControllerLib { /** * Throws if the sender is not the protocol */ function onlyGovernanceOrEmergency(IBabController _controller) internal view { require( msg.sender == _controller.owner() || msg.sender == _controller.EMERGENCY_OWNER(), 'Only governance or emergency can call this' ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // 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 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; /** * @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: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {ICurveMetaRegistry} from './ICurveMetaRegistry.sol'; /** * @title IPriceOracle * @author Babylon Finance * * Interface for interacting with PriceOracle */ interface ITokenIdentifier { /* ============ Functions ============ */ function identifyTokens( address _tokenIn, address _tokenOut, ICurveMetaRegistry _curveMetaRegistry ) external view returns ( uint8, uint8, address, address ); function updateYearnVault(address[] calldata _vaults, bool[] calldata _values) external; function updateVisor(address[] calldata _vaults, bool[] calldata _values) external; function updateSynth(address[] calldata _synths, bool[] calldata _values) external; function updateCreamPair(address[] calldata _creamTokens, address[] calldata _underlyings) external; function updateAavePair(address[] calldata _aaveTokens, address[] calldata _underlyings) external; function updateCompoundPair(address[] calldata _cTokens, address[] calldata _underlyings) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @title ICurveMetaRegistry * @author Babylon Finance * * Interface for interacting with all the curve registries */ interface ICurveMetaRegistry { /* ============ Functions ============ */ function updatePoolsList() external; function updateCryptoRegistries() external; /* ============ View Functions ============ */ function isPool(address _poolAddress) external view returns (bool); function getCoinAddresses(address _pool, bool _getUnderlying) external view returns (address[8] memory); function getNCoins(address _pool) external view returns (uint256); function getLpToken(address _pool) external view returns (address); function getPoolFromLpToken(address _lpToken) external view returns (address); function getVirtualPriceFromLpToken(address _pool) external view returns (uint256); function isMeta(address _pool) external view returns (bool); function getUnderlyingAndRate(address _pool, uint256 _i) external view returns (address, uint256); function findPoolForCoins( address _fromToken, address _toToken, uint256 _i ) external view returns (address); function getCoinIndices( address _pool, address _fromToken, address _toToken ) external view returns ( uint256, uint256, bool ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IBaseIntegration} from '../interfaces/IBaseIntegration.sol'; /** * @title ITrade * @author Babylon Finance * * Interface for trading protocol integrations */ interface ITradeIntegration is IBaseIntegration { function trade( address _strategy, address _sendToken, uint256 _sendQuantity, address _receiveToken, uint256 _minReceiveQuantity ) external; function trade( address _strategy, address _sendToken, uint256 _sendQuantity, address _receiveToken, uint256 _minReceiveQuantity, address _hopToken ) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; interface IBaseIntegration { function name() external view returns (string memory); } // 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; } }
Resolves garden votes for this cycle Note: Only keeper can call this _gardens Gardens that are going to receive investment _weights Weight for the investment in each garden normalied to 1e18 precision/
function resolveGardenVotes(address[] memory _gardens, uint256[] memory _weights) public override { _onlyKeeper(); _require(_gardens.length == _weights.length, Errors.HEART_VOTES_LENGTH); delete votedGardens; delete gardenWeights; for (uint256 i = 0; i < _gardens.length; i++) { votedGardens.push(_gardens[i]); gardenWeights.push(_weights[i]); } lastVotesAt = block.timestamp; emit UpdatedGardenWeights(block.timestamp); }
217,632
./full_match/5/0xd7A541c394f943F73D3267d64Eb8A32D690D0a80/sources/Casino.sol
Generates a number between 1 and 10 that will be the winner
function generateNumberWinner() public { distributePrizes(numberGenerated); }
1,850,310
./full_match/1/0xd15563162301EcD765bFB54eBd0809b21932C506/sources/contracts/lib/SlotsLib.sol
Pushes an address to the array
function push(bytes32 slot, address value) internal { uint length = arrayLength(slot); setAt(slot, length, value); setLength(slot, length + 1); }
3,877,049
// SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../interfaces/IOutputReceiver.sol"; import "../../interfaces/IOutputReceiverV2.sol"; import "../../interfaces/IOutputReceiverV3.sol"; import "../../interfaces/IRevest.sol"; import "../../interfaces/IAddressRegistry.sol"; import "../../interfaces/IRewardsHandler.sol"; import "../../interfaces/IFNFTHandler.sol"; import "../../interfaces/IAddressLock.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; contract Staking is Ownable, IOutputReceiverV3, ERC165, IAddressLock { using SafeERC20 for IERC20; address private revestAddress; address public lpAddress; address public rewardsHandlerAddress; address public addressRegistry; address public oldStakingContract; uint public previousStakingIDCutoff; bool public additionalEnabled; uint private constant ONE_DAY = 86400; uint private constant WINDOW_ONE = ONE_DAY; uint private constant WINDOW_THREE = ONE_DAY*5; uint private constant WINDOW_SIX = ONE_DAY*9; uint private constant WINDOW_TWELVE = ONE_DAY*14; uint private constant MAX_INT = 2**256 - 1; // For tracking if a given contract has approval for token mapping (address => mapping (address => bool)) private approvedContracts; address internal immutable WETH; uint[4] internal interestRates = [4, 13, 27, 56]; string public customMetadataUrl = "https://revest.mypinata.cloud/ipfs/QmdaJso83dhA5My9gz3ewXBxoWveo95utJJqY99ZSGEpRc"; string public addressMetadataUrl = "https://revest.mypinata.cloud/ipfs/QmWUyvkGFtFRXWxneojvAfBMy8QpewSvwQMQAkAUV42A91"; event StakedRevest(uint indexed timePeriod, bool indexed isBasic, uint indexed amount, uint fnftId); struct StakingData { uint timePeriod; uint dateLockedFrom; uint amount; } // fnftId -> timePeriods mapping(uint => StakingData) public stakingConfigs; constructor( address revestAddress_, address lpAddress_, address rewardsHandlerAddress_, address addressRegistry_, address wrappedEth_ ) { revestAddress = revestAddress_; lpAddress = lpAddress_; addressRegistry = addressRegistry_; rewardsHandlerAddress = rewardsHandlerAddress_; WETH = wrappedEth_; previousStakingIDCutoff = IFNFTHandler(IAddressRegistry(addressRegistry).getRevestFNFT()).getNextId() - 1; address revest = address(getRevest()); IERC20(lpAddress).approve(revest, MAX_INT); IERC20(revestAddress).approve(revest, MAX_INT); approvedContracts[revest][lpAddress] = true; approvedContracts[revest][revestAddress] = true; } function supportsInterface(bytes4 interfaceId) public view override (ERC165, IERC165) returns (bool) { return ( interfaceId == type(IOutputReceiver).interfaceId || interfaceId == type(IAddressLock).interfaceId || interfaceId == type(IOutputReceiverV2).interfaceId || interfaceId == type(IOutputReceiverV3).interfaceId || super.supportsInterface(interfaceId) ); } function stakeBasicTokens(uint amount, uint monthsMaturity) public returns (uint) { return _stake(revestAddress, amount, monthsMaturity); } function stakeLPTokens(uint amount, uint monthsMaturity) public returns (uint) { return _stake(lpAddress, amount, monthsMaturity); } function claimRewards(uint fnftId) external { // Check to make sure user owns the fnftId require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(_msgSender(), fnftId) == 1, 'E061'); // Receive rewards IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, _msgSender()); } /// /// Address Lock Features /// function updateLock(uint fnftId, uint, bytes memory) external override { require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(_msgSender(), fnftId) == 1, 'E061'); // Receive rewards IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, _msgSender()); } // This function not utilized function createLock(uint, uint, bytes memory) external pure override { return; } /// /// Output Recevier Functions /// function receiveRevestOutput( uint fnftId, address asset, address payable owner, uint quantity ) external override { address vault = getRegistry().getTokenVault(); require(_msgSender() == vault, "E016"); require(quantity == 1, 'ONLY SINGULAR'); // Strictly limit access require(fnftId <= previousStakingIDCutoff || stakingConfigs[fnftId].timePeriod > 0, 'Nonexistent!'); uint totalQuantity = getValue(fnftId); IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, owner); if (asset == revestAddress) { IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, 0); } else if (asset == lpAddress) { IRewardsHandler(rewardsHandlerAddress).updateLPShares(fnftId, 0); } else { require(false, "E072"); } IERC20(asset).safeTransfer(owner, totalQuantity); emit WithdrawERC20OutputReceiver(_msgSender(), asset, totalQuantity, fnftId, ''); } function handleTimelockExtensions(uint fnftId, uint expiration, address caller) external override {} function handleAdditionalDeposit(uint fnftId, uint amountToDeposit, uint quantity, address caller) external override { require(_msgSender() == getRegistry().getRevest(), "E016"); require(quantity == 1); require(additionalEnabled, 'Not allowed!'); _depositAdditionalToStake(fnftId, amountToDeposit, caller); } function handleSplitOperation(uint fnftId, uint[] memory proportions, uint quantity, address caller) external override {} // Future proofing for secondary callbacks during withdrawal // Could just use triggerOutputReceiverUpdate and call withdrawal function // But deliberately using reentry is poor form and reminds me too much of OAuth 2.0 function receiveSecondaryCallback( uint fnftId, address payable owner, uint quantity, IRevest.FNFTConfig memory config, bytes memory args ) external payable override {} // Allows for similar function to address lock, updating state while still locked // Called by the user directly function triggerOutputReceiverUpdate( uint fnftId, bytes memory args ) external override {} // This function should only ever be called when a split or additional deposit has occurred function handleFNFTRemaps(uint, uint[] memory, address, bool) external pure override { revert(); } function _stake(address stakeToken, uint amount, uint monthsMaturity) private returns (uint){ require (stakeToken == lpAddress || stakeToken == revestAddress, "E079"); require(monthsMaturity == 1 || monthsMaturity == 3 || monthsMaturity == 6 || monthsMaturity == 12, 'E055'); IERC20(stakeToken).safeTransferFrom(msg.sender, address(this), amount); IRevest.FNFTConfig memory fnftConfig; fnftConfig.asset = stakeToken; fnftConfig.depositAmount = amount; fnftConfig.isMulti = true; fnftConfig.pipeToContract = address(this); address[] memory recipients = new address[](1); recipients[0] = _msgSender(); uint[] memory quantities = new uint[](1); quantities[0] = 1; address revest = getRegistry().getRevest(); if(!approvedContracts[revest][stakeToken]){ IERC20(stakeToken).approve(revest, MAX_INT); approvedContracts[revest][stakeToken] = true; } uint fnftId = IRevest(revest).mintAddressLock(address(this), '', recipients, quantities, fnftConfig); uint interestRate = getInterestRate(monthsMaturity); uint allocPoint = amount * interestRate; StakingData memory cfg = StakingData(monthsMaturity, block.timestamp, amount); stakingConfigs[fnftId] = cfg; if(stakeToken == lpAddress) { IRewardsHandler(rewardsHandlerAddress).updateLPShares(fnftId, allocPoint); } else if (stakeToken == lpAddress) { IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, allocPoint); } emit StakedRevest(monthsMaturity, stakeToken == revestAddress, amount, fnftId); emit DepositERC20OutputReceiver(_msgSender(), stakeToken, amount, fnftId, ''); return fnftId; } function _depositAdditionalToStake(uint fnftId, uint amount, address caller) private { //Prevent unauthorized access require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(caller, fnftId) == 1, 'E061'); require(fnftId > previousStakingIDCutoff, 'E080'); uint time = stakingConfigs[fnftId].timePeriod; require(time > 0, 'E078'); address asset = ITokenVault(getRegistry().getTokenVault()).getFNFT(fnftId).asset; require(asset == revestAddress || asset == lpAddress, 'E079'); //Claim rewards owed IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, _msgSender()); //Write new, extended unlock date stakingConfigs[fnftId].dateLockedFrom = block.timestamp; stakingConfigs[fnftId].amount = stakingConfigs[fnftId].amount + amount; //Retreive current allocation points – WETH and RVST implicitly have identical alloc points uint oldAllocPoints = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, asset == revestAddress); uint allocPoints = amount * getInterestRate(time) + oldAllocPoints; if(asset == revestAddress) { IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, allocPoints); } else if (asset == lpAddress) { IRewardsHandler(rewardsHandlerAddress).updateLPShares(fnftId, allocPoints); } emit DepositERC20OutputReceiver(_msgSender(), asset, amount, fnftId, ''); } /// /// VIEW FUNCTIONS /// /// Custom view function function getInterestRate(uint months) public view returns (uint) { if (months <= 1) { return interestRates[0]; } else if (months <= 3) { return interestRates[1]; } else if (months <= 6) { return interestRates[2]; } else { return interestRates[3]; } } function getRevest() private view returns (IRevest) { return IRevest(getRegistry().getRevest()); } function getRegistry() public view returns (IAddressRegistry) { return IAddressRegistry(addressRegistry); } function getWindow(uint timePeriod) public pure returns (uint window) { if(timePeriod == 1) { window = WINDOW_ONE; } if(timePeriod == 3) { window = WINDOW_THREE; } if(timePeriod == 6) { window = WINDOW_SIX; } if(timePeriod == 12) { window = WINDOW_TWELVE; } } /// ADDRESS REGISTRY VIEW FUNCTIONS /// Does the address lock need an update? function needsUpdate() external pure override returns (bool) { return true; } /// Get the metadata URL for an address lock function getMetadata() external view override returns (string memory) { return addressMetadataUrl; } /// Can the stake be unlocked? function isUnlockable(uint fnftId, uint) external view override returns (bool) { if(fnftId <= previousStakingIDCutoff) { return Staking(oldStakingContract).isUnlockable(fnftId, 0); } uint timePeriod = stakingConfigs[fnftId].timePeriod; uint depositTime = stakingConfigs[fnftId].dateLockedFrom; uint window = getWindow(timePeriod); bool mature = block.timestamp - depositTime > (timePeriod * 30 * ONE_DAY); bool window_open = (block.timestamp - depositTime) % (timePeriod * 30 * ONE_DAY) < window; return mature && window_open; } // Retrieve encoded data on the state of the stake for the address lock component function getDisplayValues(uint fnftId, uint) external view override returns (bytes memory) { if(fnftId <= previousStakingIDCutoff) { return IAddressLock(oldStakingContract).getDisplayValues(fnftId, 0); } uint allocPoints; { uint revestTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint lpTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, false); allocPoints = revestTokenAlloc > 0 ? revestTokenAlloc : lpTokenAlloc; } uint timePeriod = stakingConfigs[fnftId].timePeriod; return abi.encode(allocPoints, timePeriod); } /// OUTPUT RECEVIER VIEW FUNCTIONS function getCustomMetadata(uint fnftId) external view override returns (string memory) { if(fnftId <= previousStakingIDCutoff) { return Staking(oldStakingContract).getCustomMetadata(fnftId); } else { return customMetadataUrl; } } function getOutputDisplayValues(uint fnftId) external view override returns (bytes memory) { if(fnftId <= previousStakingIDCutoff) { return IOutputReceiver(oldStakingContract).getOutputDisplayValues(fnftId); } bool isRevestToken; { // Will be zero if this is an LP stake uint revestTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint wethTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, WETH, true); isRevestToken = revestTokenAlloc > 0 || wethTokenAlloc > 0; } uint revestRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, revestAddress); uint wethRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, WETH); uint timePeriod = stakingConfigs[fnftId].timePeriod; uint nextUnlock = block.timestamp + ((timePeriod * 30 days) - ((block.timestamp - stakingConfigs[fnftId].dateLockedFrom) % (timePeriod * 30 days))); //This parameter has been modified for new stakes return abi.encode(revestRewards, wethRewards, timePeriod, stakingConfigs[fnftId].dateLockedFrom, isRevestToken ? revestAddress : lpAddress, nextUnlock); } function getAddressRegistry() external view override returns (address) { return addressRegistry; } function getValue(uint fnftId) public view override returns (uint) { if(fnftId <= previousStakingIDCutoff) { return ITokenVault(getRegistry().getTokenVault()).getFNFT(fnftId).depositAmount; } else { return stakingConfigs[fnftId].amount; } } function getAsset(uint fnftId) external view override returns (address) { return ITokenVault(getRegistry().getTokenVault()).getFNFT(fnftId).asset; } /// /// ADMIN FUNCTIONS /// // Allows us to set a new output receiver metadata URL function setCustomMetadata(string memory _customMetadataUrl) external onlyOwner { customMetadataUrl = _customMetadataUrl; } function setLPAddress(address lpAddress_) external onlyOwner { lpAddress = lpAddress_; } function setAddressRegistry(address addressRegistry_) external override onlyOwner { addressRegistry = addressRegistry_; } // Set a new metadata url for address lock function setMetadata(string memory _addressMetadataUrl) external onlyOwner { addressMetadataUrl = _addressMetadataUrl; } // What contract will handle staking rewards function setRewardsHandler(address _handler) external onlyOwner { rewardsHandlerAddress = _handler; } function setCutoff(uint cutoff) external onlyOwner { previousStakingIDCutoff = cutoff; } function setOldStaking(address stake) external onlyOwner { oldStakingContract = stake; } function setAdditionalDepositsEnabled(bool enabled) external onlyOwner { additionalEnabled = enabled; } } // 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: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IRegistryProvider.sol"; import '@openzeppelin/contracts/utils/introspection/IERC165.sol'; /** * @title Provider interface for Revest FNFTs */ interface IOutputReceiver is IRegistryProvider, IERC165 { function receiveRevestOutput( uint fnftId, address asset, address payable owner, uint quantity ) external; function getCustomMetadata(uint fnftId) external view returns (string memory); function getValue(uint fnftId) external view returns (uint); function getAsset(uint fnftId) external view returns (address); function getOutputDisplayValues(uint fnftId) external view returns (bytes memory); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IOutputReceiver.sol"; import "./IRevest.sol"; import '@openzeppelin/contracts/utils/introspection/IERC165.sol'; /** * @title Provider interface for Revest FNFTs */ interface IOutputReceiverV2 is IOutputReceiver { // Future proofing for secondary callbacks during withdrawal // Could just use triggerOutputReceiverUpdate and call withdrawal function // But deliberately using reentry is poor form and reminds me too much of OAuth 2.0 function receiveSecondaryCallback( uint fnftId, address payable owner, uint quantity, IRevest.FNFTConfig memory config, bytes memory args ) external payable; // Allows for similar function to address lock, updating state while still locked // Called by the user directly function triggerOutputReceiverUpdate( uint fnftId, bytes memory args ) external; // This function should only ever be called when a split or additional deposit has occurred function handleFNFTRemaps(uint fnftId, uint[] memory newFNFTIds, address caller, bool cleanup) external; } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IOutputReceiverV2.sol"; /** * @title Provider interface for Revest FNFTs */ interface IOutputReceiverV3 is IOutputReceiverV2 { event DepositERC20OutputReceiver(address indexed mintTo, address indexed token, uint amountTokens, uint indexed fnftId, bytes extraData); event DepositERC721OutputReceiver(address indexed mintTo, address indexed token, uint[] tokenIds, uint indexed fnftId, bytes extraData); event DepositERC1155OutputReceiver(address indexed mintTo, address indexed token, uint tokenId, uint amountTokens, uint indexed fnftId, bytes extraData); event WithdrawERC20OutputReceiver(address indexed caller, address indexed token, uint amountTokens, uint indexed fnftId, bytes extraData); event WithdrawERC721OutputReceiver(address indexed caller, address indexed token, uint[] tokenIds, uint indexed fnftId, bytes extraData); event WithdrawERC1155OutputReceiver(address indexed caller, address indexed token, uint tokenId, uint amountTokens, uint indexed fnftId, bytes extraData); function handleTimelockExtensions(uint fnftId, uint expiration, address caller) external; function handleAdditionalDeposit(uint fnftId, uint amountToDeposit, uint quantity, address caller) external; function handleSplitOperation(uint fnftId, uint[] memory proportions, uint quantity, address caller) external; } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; interface IRevest { event FNFTTimeLockMinted( address indexed asset, address indexed from, uint indexed fnftId, uint endTime, uint[] quantities, FNFTConfig fnftConfig ); event FNFTValueLockMinted( address indexed asset, address indexed from, uint indexed fnftId, address compareTo, address oracleDispatch, uint[] quantities, FNFTConfig fnftConfig ); event FNFTAddressLockMinted( address indexed asset, address indexed from, uint indexed fnftId, address trigger, uint[] quantities, FNFTConfig fnftConfig ); event FNFTWithdrawn( address indexed from, uint indexed fnftId, uint indexed quantity ); event FNFTSplit( address indexed from, uint[] indexed newFNFTId, uint[] indexed proportions, uint quantity ); event FNFTUnlocked( address indexed from, uint indexed fnftId ); event FNFTMaturityExtended( address indexed from, uint indexed fnftId, uint indexed newExtendedTime ); event FNFTAddionalDeposited( address indexed from, uint indexed newFNFTId, uint indexed quantity, uint amount ); struct FNFTConfig { address asset; // The token being stored address pipeToContract; // Indicates if FNFT will pipe to another contract uint depositAmount; // How many tokens uint depositMul; // Deposit multiplier uint split; // Number of splits remaining uint depositStopTime; // bool maturityExtension; // Maturity extensions remaining bool isMulti; // bool nontransferrable; // False by default (transferrable) // } // Refers to the global balance for an ERC20, encompassing possibly many FNFTs struct TokenTracker { uint lastBalance; uint lastMul; } enum LockType { DoesNotExist, TimeLock, ValueLock, AddressLock } struct LockParam { address addressLock; uint timeLockExpiry; LockType lockType; ValueLock valueLock; } struct Lock { address addressLock; LockType lockType; ValueLock valueLock; uint timeLockExpiry; uint creationTime; bool unlocked; } struct ValueLock { address asset; address compareTo; address oracle; uint unlockValue; bool unlockRisingEdge; } function mintTimeLock( uint endTime, address[] memory recipients, uint[] memory quantities, IRevest.FNFTConfig memory fnftConfig ) external payable returns (uint); function mintValueLock( address primaryAsset, address compareTo, uint unlockValue, bool unlockRisingEdge, address oracleDispatch, address[] memory recipients, uint[] memory quantities, IRevest.FNFTConfig memory fnftConfig ) external payable returns (uint); function mintAddressLock( address trigger, bytes memory arguments, address[] memory recipients, uint[] memory quantities, IRevest.FNFTConfig memory fnftConfig ) external payable returns (uint); function withdrawFNFT(uint tokenUID, uint quantity) external; function unlockFNFT(uint tokenUID) external; function splitFNFT( uint fnftId, uint[] memory proportions, uint quantity ) external returns (uint[] memory newFNFTIds); function depositAdditionalToFNFT( uint fnftId, uint amount, uint quantity ) external returns (uint); function extendFNFTMaturity( uint fnftId, uint endTime ) external returns (uint); function setFlatWeiFee(uint wethFee) external; function setERC20Fee(uint erc20) external; function getFlatWeiFee() external view returns (uint); function getERC20Fee() external view returns (uint); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; /** * @title Provider interface for Revest FNFTs * @dev * */ interface IAddressRegistry { function initialize( address lock_manager_, address liquidity_, address revest_token_, address token_vault_, address revest_, address fnft_, address metadata_, address admin_, address rewards_ ) external; function getAdmin() external view returns (address); function setAdmin(address admin) external; function getLockManager() external view returns (address); function setLockManager(address manager) external; function getTokenVault() external view returns (address); function setTokenVault(address vault) external; function getRevestFNFT() external view returns (address); function setRevestFNFT(address fnft) external; function getMetadataHandler() external view returns (address); function setMetadataHandler(address metadata) external; function getRevest() external view returns (address); function setRevest(address revest) external; function getDEX(uint index) external view returns (address); function setDex(address dex) external; function getRevestToken() external view returns (address); function setRevestToken(address token) external; function getRewardsHandler() external view returns(address); function setRewardsHandler(address esc) external; function getAddress(bytes32 id) external view returns (address); function getLPs() external view returns (address); function setLPs(address liquidToken) external; } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; interface IRewardsHandler { struct UserBalance { uint allocPoint; // Allocation points uint lastMul; } function receiveFee(address token, uint amount) external; function updateLPShares(uint fnftId, uint newShares) external; function updateBasicShares(uint fnftId, uint newShares) external; function getAllocPoint(uint fnftId, address token, bool isBasic) external view returns (uint); function claimRewards(uint fnftId, address caller) external returns (uint); function setStakingContract(address stake) external; function getRewards(uint fnftId, address token) external view returns (uint); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; interface IFNFTHandler { function mint(address account, uint id, uint amount, bytes memory data) external; function mintBatchRec(address[] memory recipients, uint[] memory quantities, uint id, uint newSupply, bytes memory data) external; function mintBatch(address to, uint[] memory ids, uint[] memory amounts, bytes memory data) external; function setURI(string memory newuri) external; function burn(address account, uint id, uint amount) external; function burnBatch(address account, uint[] memory ids, uint[] memory amounts) external; function getBalance(address tokenHolder, uint id) external view returns (uint); function getSupply(uint fnftId) external view returns (uint); function getNextId() external view returns (uint); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IRegistryProvider.sol"; import '@openzeppelin/contracts/utils/introspection/IERC165.sol'; /** * @title Provider interface for Revest FNFTs * @dev Address locks MUST be non-upgradeable to be considered for trusted status * @author Revest */ interface IAddressLock is IRegistryProvider, IERC165{ /// Creates a lock to the specified lockID /// @param fnftId the fnftId to map this lock to. Not recommended for typical locks, as it will break on splitting /// @param lockId the lockId to map this lock to. Recommended uint for storing references to lock configurations /// @param arguments an abi.encode() bytes array. Allows frontend to encode and pass in an arbitrary set of parameters /// @dev creates a lock for the specified lockId. Will be called during the creation process for address locks when the address /// of a contract implementing this interface is passed in as the "trigger" address for minting an address lock. The bytes /// representing any parameters this lock requires are passed through to this method, where abi.decode must be call on them function createLock(uint fnftId, uint lockId, bytes memory arguments) external; /// Updates a lock at the specified lockId /// @param fnftId the fnftId that can map to a lock config stored in implementing contracts. Not recommended, as it will break on splitting /// @param lockId the lockId that maps to the lock config which should be updated. Recommended for retrieving references to lock configurations /// @param arguments an abi.encode() bytes array. Allows frontend to encode and pass in an arbitrary set of parameters /// @dev updates a lock for the specified lockId. Will be called by the frontend from the information section if an update is requested /// can further accept and decode parameters to use in modifying the lock's config or triggering other actions /// such as triggering an on-chain oracle to update function updateLock(uint fnftId, uint lockId, bytes memory arguments) external; /// Whether or not the lock can be unlocked /// @param fnftId the fnftId that can map to a lock config stored in implementing contracts. Not recommended, as it will break on splitting /// @param lockId the lockId that maps to the lock config which should be updated. Recommended for retrieving references to lock configurations /// @dev this method is called during the unlocking and withdrawal processes by the Revest contract - it is also used by the frontend /// if this method is returning true and someone attempts to unlock or withdraw from an FNFT attached to the requested lock, the request will succeed /// @return whether or not this lock may be unlocked function isUnlockable(uint fnftId, uint lockId) external view returns (bool); /// Provides an encoded bytes arary that represents values this lock wants to display on the info screen /// Info to decode these values is provided in the metadata file /// @param fnftId the fnftId that can map to a lock config stored in implementing contracts. Not recommended, as it will break on splitting /// @param lockId the lockId that maps to the lock config which should be updated. Recommended for retrieving references to lock configurations /// @dev used by the frontend to fetch on-chain data on the state of any given lock /// @return a bytes array that represents the result of calling abi.encode on values which the developer wants to appear on the frontend function getDisplayValues(uint fnftId, uint lockId) external view returns (bytes memory); /// Maps to a URL, typically IPFS-based, that contains information on how to encode and decode paramters sent to and from this lock /// Please see additional documentation for JSON config info /// @dev this method will be called by the frontend only but is crucial to properly implement for proper minting and information workflows /// @return a URL to the JSON file containing this lock's metadata schema function getMetadata() external view returns (string memory); /// Whether or not this lock will need updates and should display the option for them /// @dev this will be called by the frontend to determine if update inputs and buttons should be displayed /// @return whether or not the locks created by this contract will need updates function needsUpdate() external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/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/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // 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: GNU-GPL v3.0 or later pragma solidity ^0.8.0; import "../interfaces/IAddressRegistry.sol"; import "../interfaces/ITokenVault.sol"; import "../interfaces/ILockManager.sol"; interface IRegistryProvider { function setAddressRegistry(address revest) external; function getAddressRegistry() external view returns (address); } // 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: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IRevest.sol"; interface ITokenVault { function createFNFT( uint fnftId, IRevest.FNFTConfig memory fnftConfig, uint quantity, address from ) external; function withdrawToken( uint fnftId, uint quantity, address user ) external; function depositToken( uint fnftId, uint amount, uint quantity ) external; function cloneFNFTConfig(IRevest.FNFTConfig memory old) external returns (IRevest.FNFTConfig memory); function mapFNFTToToken( uint fnftId, IRevest.FNFTConfig memory fnftConfig ) external; function handleMultipleDeposits( uint fnftId, uint newFNFTId, uint amount ) external; function splitFNFT( uint fnftId, uint[] memory newFNFTIds, uint[] memory proportions, uint quantity ) external; function getFNFT(uint fnftId) external view returns (IRevest.FNFTConfig memory); function getFNFTCurrentValue(uint fnftId) external view returns (uint); function getNontransferable(uint fnftId) external view returns (bool); function getSplitsRemaining(uint fnftId) external view returns (uint); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IRevest.sol"; interface ILockManager { function createLock(uint fnftId, IRevest.LockParam memory lock) external returns (uint); function getLock(uint lockId) external view returns (IRevest.Lock memory); function fnftIdToLockId(uint fnftId) external view returns (uint); function fnftIdToLock(uint fnftId) external view returns (IRevest.Lock memory); function pointFNFTToLock(uint fnftId, uint lockId) external; function lockTypes(uint tokenId) external view returns (IRevest.LockType); function unlockFNFT(uint fnftId, address sender) external returns (bool); function getLockMaturity(uint fnftId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
Will be zero if this is an LP stake
function getOutputDisplayValues(uint fnftId) external view override returns (bytes memory) { if(fnftId <= previousStakingIDCutoff) { return IOutputReceiver(oldStakingContract).getOutputDisplayValues(fnftId); } bool isRevestToken; { uint revestTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint wethTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, WETH, true); isRevestToken = revestTokenAlloc > 0 || wethTokenAlloc > 0; } uint revestRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, revestAddress); uint wethRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, WETH); uint timePeriod = stakingConfigs[fnftId].timePeriod; uint nextUnlock = block.timestamp + ((timePeriod * 30 days) - ((block.timestamp - stakingConfigs[fnftId].dateLockedFrom) % (timePeriod * 30 days))); }
1,669,473
pragma solidity 0.6.12; import '@pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/access/Ownable.sol'; import "./MySecure.sol"; import "./SyrupBar.sol"; // import "@nomiclabs/buidler/console.sol"; interface IMigratorChef { // Perform LP token migration from legacy SilverlineSwap to CakeSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to SilverlineSwap LP tokens. // CakeSwap must mint EXACTLY the same amount of CakeSwap LP tokens or // else something bad will happen. Traditional SilverlineSwap does not // do that so be careful! function migrate(IBEP20 token) external returns (IBEP20); } // MasterChef is the master of Silver. He can make Silver and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SILVER is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // 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 SILVERs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCakePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCakePerShare` (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 { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SILVERs to distribute per block. uint256 lastRewardBlock; // Last block number that SILVERs distribution occurs. uint256 accCakePerShare; // Accumulated SILVERs per share, times 1e12. See below. } // The SILVER TOKEN! MySecure public cake; // The SYRUP TOKEN! SyrupBar public syrup; // Dev address. address public devaddr; // SILVER tokens created per block. uint256 public cakePerBlock; // Bonus muliplier for early cake makers. uint256 public BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SILVER mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( MySecure _cake, SyrupBar _syrup, address _devaddr, uint256 _cakePerBlock, uint256 _startBlock ) public { cake = _cake; syrup = _syrup; devaddr = _devaddr; cakePerBlock = _cakePerBlock; startBlock = _startBlock; // staking pool poolInfo.push(PoolInfo({ lpToken: _cake, allocPoint: 1000, lastRewardBlock: startBlock, accCakePerShare: 0 })); totalAllocPoint = 1000; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IBEP20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCakePerShare: 0 })); updateStakingPool(); } // Update the given pool's SILVER allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); updateStakingPool(); } } function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points); poolInfo[0].allocPoint = points; } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IBEP20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IBEP20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending SILVERs on frontend. function pendingCake(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCakePerShare = pool.accCakePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(cakePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCakePerShare = accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCakePerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(cakePerBlock).mul(pool.allocPoint).div(totalAllocPoint); cake.mint(devaddr, cakeReward.div(10)); cake.mint(address(syrup), cakeReward); pool.accCakePerShare = pool.accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SILVER allocation. function deposit(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'deposit SILVER by staking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCakeTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'withdraw SILVER by unstaking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCakeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Stake SILVER tokens to MasterChef function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCakeTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); syrup.mint(msg.sender, _amount); emit Deposit(msg.sender, 0, _amount); } // Withdraw SILVER tokens from STAKING. function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCakeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); syrup.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe cake transfer function, just in case if rounding error causes pool to not have enough SILVERs. function safeCakeTransfer(address _to, uint256 _amount) internal { syrup.safeCakeTransfer(_to, _amount); } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.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; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // 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; } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @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; import './IBEP20.sol'; import '../../math/SafeMath.sol'; import '../../utils/Address.sol'; /** * @title SafeBEP20 * @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer( IBEP20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IBEP20 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 * {IBEP20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IBEP20 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), 'SafeBEP20: approve from non-zero to non-zero allowance' ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IBEP20 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( IBEP20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, 'SafeBEP20: 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(IBEP20 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, 'SafeBEP20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed'); } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; import '../GSN/Context.sol'; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.6.12; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/BEP20.sol"; // MySecure with Governance. contract MySecure is BEP20('MySecure', 'MYSEC') { /// @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); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @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), "MYSEC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MYSEC::delegateBySig: invalid nonce"); require(now <= expiry, "MYSEC::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, "MYSEC::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); // balance of underlying SILVERs (not scaled); _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, "MYSEC::_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; } } pragma solidity 0.6.12; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/BEP20.sol"; import "./MySecure.sol"; // SyrupBar with Governance. contract SyrupBar is BEP20('SyrupBar Token', 'SYRUP') { /// @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); _moveDelegates(address(0), _delegates[_to], _amount); } function burn(address _from ,uint256 _amount) public onlyOwner { _burn(_from, _amount); _moveDelegates(_delegates[_from], address(0), _amount); } // The SILVER TOKEN! MySecure public cake; constructor( MySecure _cake ) public { cake = _cake; } // Safe cake transfer function, just in case if rounding error causes pool to not have enough SILVERs. function safeCakeTransfer(address _to, uint256 _amount) public onlyOwner { uint256 cakeBal = cake.balanceOf(address(this)); if (_amount > cakeBal) { cake.transfer(_to, cakeBal); } else { cake.transfer(_to, _amount); } } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @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), "MYSEC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MYSEC::delegateBySig: invalid nonce"); require(now <= expiry, "MYSEC::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, "MYSEC::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); // balance of underlying SILVERs (not scaled); _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, "MYSEC::_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; } } // SPDX-License-Identifier: MIT 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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'Address: low-level call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, 'Address: low-level call with value failed'); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, 'Address: insufficient balance for call'); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), 'Address: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.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 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; import '../../access/Ownable.sol'; import '../../GSN/Context.sol'; import './IBEP20.sol'; import '../../math/SafeMath.sol'; import '../../utils/Address.sol'; /** * @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 BEP20 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 {IBEP20-approve}. */ contract BEP20 is Context, IBEP20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; 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 bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'BEP20: 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 {BEP20-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 {BEP20-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, 'BEP20: decreased allowance below zero') ); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); 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), 'BEP20: transfer from the zero address'); require(recipient != address(0), 'BEP20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'BEP20: 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), 'BEP20: 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), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'BEP20: 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), 'BEP20: approve from the zero address'); require(spender != address(0), 'BEP20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev 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, 'BEP20: burn amount exceeds allowance') ); } }
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, 'BEP20: burn amount exceeds allowance') ); }
250,545
pragma solidity ^0.5.0; // Copyright 2018 OpenST Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import "../lib/Block.sol"; import "../lib/MetaBlock.sol"; import "../lib/SafeMath.sol"; import "./BlockStoreInterface.sol"; import "./OriginTransitionObjectInterface.sol"; /** * @title A block store stores blocks of a block chain. * * @notice The block store stores headers of blocks. Not all headers have to be * reported. It is only required to report all headers that should * become justified checkpoints. * The block store tracks all justifications and finalisations through * calls to the `justify()` method. Only the polling place can call * that method. */ contract BlockStore is BlockStoreInterface, OriginTransitionObjectInterface { using SafeMath for uint256; /* Events */ /** Logs that a block has been reported. */ event BlockReported(bytes32 blockHash); /** Logs that a block has been justified. */ event BlockJustified(bytes32 blockHash); /** Logs that a block has been finalised. */ event BlockFinalised(bytes32 blockHash); /* Structs */ /** A casper FFG checkpoint. */ struct Checkpoint { /** The block hash of the block at this checkpoint. */ bytes32 blockHash; /** The hash of the block of the parent checkpoint (not block) */ bytes32 parent; /** Is true if the checkpoint has been justified. */ bool justified; /** Is true if the checkpoint has been finalised. */ bool finalised; /** * The dynasty of block b is the number of finalized checkpoints in the * chain from the starting checkpoint to the parent of block b. */ uint256 dynasty; } /* Public Variables */ /** * The core identifier identifies the chain that this block store is * tracking. */ bytes20 internal coreIdentifier; /** * The epoch length is the number of blocks from one checkpoint to the * next. */ uint256 public epochLength; /** * If this block store doesn't start tracking a chain from origin, then the * starting height is the first block of the block chain where tracking * starts. For the purpose of Casper FFG it is considered the genesis. */ uint256 public startingHeight; /** * The address of the polling place address. Only the polling place may * call the justify method. */ address public pollingPlace; /** A mapping of block hashes to their reported headers. */ mapping (bytes32 => Block.Header) internal reportedBlocks; /** A mapping of block headers to their recorded checkpoints. */ mapping (bytes32 => Checkpoint) public checkpoints; /** The block hash of the highest finalised checkpoint. */ bytes32 internal head; /** * The current dynasty. The highest finalised checkpoint's dynasty is one * less. */ uint256 internal currentDynasty; /* Modifiers */ /** * @notice Functions with this modifier can only be called from the address * that is registered as the pollingPlace. */ modifier onlyPollingPlace() { require( msg.sender == pollingPlace, "This method must be called from the registered polling place." ); _; } /* Constructor */ /** * @notice Construct a new block store. Requires the block hash, state * root, and block height of an initial starting block. Depending * on which chain this store tracks, this could be a different * block than genesis. * * @param _coreIdentifier The core identifier identifies the chain that * this block store is tracking. * @param _epochLength The epoch length is the number of blocks from one * checkpoint to the next. * @param _pollingPlace The address of the polling place address. Only the * polling place may call the justify method. * @param _initialBlockHash The block hash of the initial starting block. * @param _initialStateRoot The state root of the initial starting block. * @param _initialBlockHeight The block height of the initial starting * block. */ constructor ( bytes20 _coreIdentifier, uint256 _epochLength, address _pollingPlace, bytes32 _initialBlockHash, bytes32 _initialStateRoot, uint256 _initialBlockHeight ) public { require( _epochLength > 0, "Epoch length must be greater zero." ); require( _pollingPlace != address(0), "Address of polling place must not be zero." ); require( _initialBlockHash != bytes32(0), "Initial block hash must not be zero." ); require( _initialStateRoot != bytes32(0), "Initial state root must not be zero." ); require( _initialBlockHeight.mod(_epochLength) == 0, "The initial block height is incompatible to the epoch length. Must be a multiple." ); coreIdentifier = _coreIdentifier; epochLength = _epochLength; pollingPlace = _pollingPlace; startingHeight = _initialBlockHeight; reportedBlocks[_initialBlockHash] = Block.Header( _initialBlockHash, bytes32(0), bytes32(0), address(0), _initialStateRoot, bytes32(0), bytes32(0), new bytes(0), uint256(0), _initialBlockHeight, uint64(0), uint64(0), uint256(0), new bytes(0), bytes32(0), uint256(0) ); checkpoints[_initialBlockHash] = Checkpoint( _initialBlockHash, bytes32(0), true, true, uint256(0) ); currentDynasty = uint256(1); } /* External Functions */ /** * @notice Returns the current head that is finalized in the block store. * * @return head_ The block hash of the head. */ function getHead() external view returns (bytes32 head_) { head_ = head; } /** * @notice Returns the current dynasty in the block store. * * @return dynasty_ The current dynasty. */ function getCurrentDynasty() external view returns (uint256 dynasty_) { dynasty_ = currentDynasty; } /** * @notice Report a block. A reported block header is stored and can then * be part of subsequent votes. * * @param _blockHeaderRlp The header of the reported block, RLP encoded. */ function reportBlock( bytes calldata _blockHeaderRlp ) external returns (bool success_) { Block.Header memory header = Block.decodeHeader(_blockHeaderRlp); success_ = reportBlock_(header); } /** * @notice Marks a block in the block store as justified. The source and * the target are required to know when a block is finalised. * Only the polling place may call this method. * * @param _sourceBlockHash The block hash of the source of the super- * majority link. * @param _targetBlockHash The block hash of the block that is justified. */ function justify( bytes32 _sourceBlockHash, bytes32 _targetBlockHash ) external onlyPollingPlace() { justify_(_sourceBlockHash, _targetBlockHash); } /** * @notice Returns the state root of the block that is stored at the given * height. The height must be <= the height of the latest finalised * checkpoint. Only state roots of checkpoints are known. * * @param _height The block height. * * @return The state root of the block at the given height. */ function stateRoot( uint256 _height ) external view returns (bytes32 stateRoot_) { require( _height <= reportedBlocks[head].height, "The state root is only known up to the height of the last finalised checkpoint." ); require( _height >= startingHeight, "The state root is only known from the starting height upwards." ); require( isAtCheckpointHeight(_height), "The height must be at a valid checkpoint height." ); /* * Walk backwards along the list of checkpoints as long as the height * of the checkpoint is greater than the target height. */ Checkpoint storage checkpoint = checkpoints[head]; while (reportedBlocks[checkpoint.blockHash].height > _height) { checkpoint = checkpoints[checkpoint.parent]; } /* * If the height of the resulting header is different from the height * that was given, then the given height was in between two justified * checkpoints. The height was skipped over when traversing the * recorded checkpoints. */ Block.Header storage header = reportedBlocks[checkpoint.blockHash]; require( header.height == _height, "State roots are only known for heights at justified checkpoints." ); stateRoot_ = header.stateRoot; } /** * @notice Returns the core identifier of the chain that this block store * tracks. * * @return coreIdentifier_ The core identifier of the tracked chain. */ function getCoreIdentifier() external view returns (bytes20 coreIdentifier_) { coreIdentifier_ = coreIdentifier; } /** * @notice Returns the height of the latest block that has been finalised. * * @return The height of the latest finalised block. */ function latestBlockHeight() external view returns (uint256 height_) { height_ = reportedBlocks[head].height; } /** * @notice Validates a given vote. For a vote to be valid: * - The transition object must be correct * - The hashes must exist * - The blocks of the hashes must be at checkpoint heights * - The source checkpoint must be justified * - The target must be higher than the current head * * @param _transitionHash The hash of the transition object of the related * meta-block. Depends on the source block. * @param _sourceBlockHash The hash of the source checkpoint of the vote. * @param _targetBlockHash The hash of teh target checkpoint of the vote. * * @return `true` if all of the above apply and therefore the vote is * considered valid by the block store. `false` otherwise. */ function isVoteValid( bytes32 _transitionHash, bytes32 _sourceBlockHash, bytes32 _targetBlockHash ) external view returns (bool valid_) { bool sourceValid; bool targetValid; bool transitionValid; (sourceValid,) = isSourceValid(_sourceBlockHash); (targetValid,) = isTargetValid( _sourceBlockHash, _targetBlockHash ); transitionValid = isValidTransitionHash( _transitionHash, _sourceBlockHash ); valid_ = sourceValid && targetValid && transitionValid; } /** * @notice Check, whether a block with a given block hash has been reported * before. * * @param _blockHash The hash of the block that should be checked. * * @return `true` if the block has been reported before. */ function isBlockReported( bytes32 _blockHash ) external view returns (bool reported_) { reported_ = isReported(_blockHash); } /** * @notice Returns transition object at the checkpoint defined at given * block hash. * * @dev It reverts transaction if checkpoint is not defined at given * block hash. * * @param _blockHash The hash of the block for which transition object * is requested. * * @return coreIdentifier_ The core identifier identifies the chain that * this block store is tracking. * @return dynasty_ Dynasty number of checkpoint for which transition * object is requested. * @return blockHash_ Hash of the block at checkpoint. */ function transitionObjectAtBlock( bytes32 _blockHash ) external view returns(bytes20 coreIdentifier_, uint256 dynasty_, bytes32 blockHash_) { require( isCheckpoint(_blockHash), "Checkpoint not defined for given block hash." ); coreIdentifier_ = coreIdentifier; dynasty_ = checkpoints[_blockHash].dynasty; blockHash_ = checkpoints[_blockHash].blockHash; } /** * @notice Returns transition hash at the checkpoint defined at the given * block hash. * * @dev It reverts transaction if checkpoint is not defined at given * block hash. * * @param _blockHash The hash of the block for which transition object * is requested. * * @return transitionHash_ Hash of the transition object at the checkpoint. */ function transitionHashAtBlock( bytes32 _blockHash ) external view returns(bytes32 transitionHash_) { require( isCheckpoint(_blockHash), "Checkpoint not defined for given block hash." ); transitionHash_ = MetaBlock.hashOriginTransition( checkpoints[_blockHash].dynasty, _blockHash, coreIdentifier ); } /* Internal Functions */ /** * @notice Marks a block in the block store as justified. The source and * the target are required to know when a block is finalised. * * @param _sourceBlockHash The block hash of the source of the super- * majority link. * @param _targetBlockHash The block hash of the block that is justified. */ function justify_( bytes32 _sourceBlockHash, bytes32 _targetBlockHash ) internal { bool blockValid; string memory reason; (blockValid, reason) = isSourceValid(_sourceBlockHash); require(blockValid, reason); (blockValid, reason) = isTargetValid( _sourceBlockHash, _targetBlockHash ); require(blockValid, reason); // Finalise first as it may increase the dynasty number of target. if (distanceInEpochs(_sourceBlockHash, _targetBlockHash) == 1) { finalise(_sourceBlockHash); } Checkpoint memory checkpoint = Checkpoint( _targetBlockHash, _sourceBlockHash, true, false, currentDynasty ); checkpoints[_targetBlockHash] = checkpoint; emit BlockJustified(_targetBlockHash); } /** * @notice Report a block. A reported block header is stored and can then * be part of subsequent votes. * * @param _header The header object of the reported block. */ function reportBlock_( Block.Header memory _header ) internal returns (bool success_) { reportedBlocks[_header.blockHash] = _header; emit BlockReported(_header.blockHash); success_ = true; } /** * @notice Returns true if the given block hash corresponds to a block that * has been reported. * * @param _blockHash The block hash to check. * * @return `true` if the given block hash was reported before. */ function isReported( bytes32 _blockHash ) internal view returns (bool wasReported_) { wasReported_ = reportedBlocks[_blockHash].blockHash == _blockHash; } /** * @notice Checks if a target block is valid. The same criteria apply for * voting and justifying, as justifying results from voting. * * @param _sourceBlockHash The hash of the corresponding source. * @param _targetBlockHash The hash of the potential target block. * * @return valid_ `true` if the given block hash is a valid target. * @return reason_ Gives the reason in case the block is not a valid target. */ function isTargetValid( bytes32 _sourceBlockHash, bytes32 _targetBlockHash ) internal view returns (bool valid_, string memory reason_) { if (!isReported(_targetBlockHash)) { valid_ = false; reason_ = "The target block must first be reported."; } else if (!isAtCheckpointHeight(_targetBlockHash)) { valid_ = false; reason_ = "The target must be at a height that is a multiple of the epoch length."; } else if (!isAboveHead(_targetBlockHash)) { valid_ = false; reason_ = "The target must be higher than the head."; } else if (!isAbove(_targetBlockHash, _sourceBlockHash)) { valid_ = false; reason_ = "The target must be above the source in height."; } else if ( isCheckpoint(_targetBlockHash) && !isParentCheckpoint(_sourceBlockHash, _targetBlockHash) ) { valid_ = false; reason_ = "The target must not be justified already with a different source."; } else { valid_ = true; } } /** * @notice Takes a transition hash and checks that the given block results * in the same transition hash. * * @param _transitionHash The hash to check. * @param _blockHash The block to test the hash against. * * @return `true` if the given block results in the same transition hash. */ function isValidTransitionHash( bytes32 _transitionHash, bytes32 _blockHash ) internal view returns (bool valid_) { bytes32 expectedHash = MetaBlock.hashOriginTransition( checkpoints[_blockHash].dynasty, _blockHash, coreIdentifier ); valid_ = _transitionHash == expectedHash; } /** * @notice Checks whether the given block hash represents a justified * checkpoint. * * @param _blockHash The block hash for which to check. * * @return isCheckpoint_ `true` if the block hash represents a justified * checkpoint. */ function isCheckpoint( bytes32 _blockHash ) internal view returns (bool isCheckpoint_) { isCheckpoint_ = checkpoints[_blockHash].blockHash == _blockHash; } /* Private Functions */ /** * @notice Finalises the checkpoint at the given block hash. Updates the * current head and dynasty if it is above the old head. * * @param _blockHash The checkpoint that shall be finalised. */ function finalise(bytes32 _blockHash) private { checkpoints[_blockHash].finalised = true; if (reportedBlocks[_blockHash].height > reportedBlocks[head].height) { head = _blockHash; currentDynasty = currentDynasty.add(1); } emit BlockFinalised(_blockHash); } /** * @notice Checks if a source block is valid. The same criteria apply for * voting and justifying, as justifying results from voting. * * @param _sourceBlockHash The hash of the potential source block. * * @return valid_ `true` if the given block hash is a valid source. * @return reason_ Gives the reason in case the block is not a valid source. */ function isSourceValid( bytes32 _sourceBlockHash ) private view returns (bool valid_, string memory reason_) { if(!isReported(_sourceBlockHash)) { valid_ = false; reason_ = "The source block must first be reported."; } else if (!isJustified(_sourceBlockHash)) { valid_ = false; reason_ = "The source block must first be justified."; } else { valid_ = true; } } /** * @notice Returns true if the given block hash corresponds to a checkpoint * that has been justified. * * @param _blockHash The block hash to check. * * @return `true` if there exists a justified checkpoint at the given block * hash. */ function isJustified( bytes32 _blockHash ) private view returns (bool justified_) { justified_ = checkpoints[_blockHash].justified; } /** * @notice Returns true if the given block hash corresponds to a block at a * valid checkpoint height (multiple of the epoch length). * * @param _blockHash The block hash to check. * * @return `true` if the given block hash is at a valid height. */ function isAtCheckpointHeight( bytes32 _blockHash ) private view returns (bool atCheckpointHeight_) { uint256 blockHeight = reportedBlocks[_blockHash].height; atCheckpointHeight_ = isAtCheckpointHeight(blockHeight); } /** * @notice Returns true if the given height corresponds to a valid * checkpoint height (multiple of the epoch length). * * @param _height The block height to check. * * @return `true` if the given block height is at a valid height. */ function isAtCheckpointHeight( uint256 _height ) private view returns (bool atCheckpointHeight_) { atCheckpointHeight_ = _height.mod(epochLength) == 0; } /** * @notice Returns true if the first block has a greater height than the * second block. * * @param _firstBlockHash Hash of the first block. * @param _secondBlockHash Hash of the second block. * * @return `true` if the first block has a greater height than the second * block. */ function isAbove( bytes32 _firstBlockHash, bytes32 _secondBlockHash ) private view returns (bool above_) { uint256 firstHeight = reportedBlocks[_firstBlockHash].height; uint256 secondHeight = reportedBlocks[_secondBlockHash].height; above_ = firstHeight > secondHeight; } /** * @notice Returns true if the given block hash corresponds to a block that * is above the currently highest finalised checkpoint. * * @param _blockHash The block hash to check. * * @return `true` if the given block hash is above the highest finalised * checkpoint. */ function isAboveHead( bytes32 _blockHash ) private view returns (bool aboveHead_) { aboveHead_ = isAbove(_blockHash, head); } /** * @notice Calculates and returns the number of epochs between two given * blocks. * * @param _lowerBlockHash Block hash of the lower block. * @param _higherBlockHash Block hash of the higher block. * * @return The distance between the given blocks in number of epochs. */ function distanceInEpochs( bytes32 _lowerBlockHash, bytes32 _higherBlockHash ) private view returns (uint256 epochDistance_) { /* * Other parts of the code checked that the blocks are at valid heights * and in the right order so this should always calculate correctly. */ uint256 lowerHeight = reportedBlocks[_lowerBlockHash].height; uint256 higherHeight = reportedBlocks[_higherBlockHash].height; uint256 blockDistance = higherHeight.sub(lowerHeight); epochDistance_ = blockDistance.div(epochLength); } /** * @notice Checks whether the older checkpoint is the parent of the * younger checkpoint. * * @param _olderBlockHash The block hash representing the older checkpoint. * @param _youngerBlockHash The block hash representing the younger * checkpoint. * * @return isParent_ `true` if the older is the parent of the younger. */ function isParentCheckpoint( bytes32 _olderBlockHash, bytes32 _youngerBlockHash ) private view returns (bool isParent_) { isParent_ = checkpoints[_youngerBlockHash].parent == _olderBlockHash; } }
Returns the core identifier of the chain that this block store tracks. return coreIdentifier_ The core identifier of the tracked chain./
function getCoreIdentifier() external view returns (bytes20 coreIdentifier_) { coreIdentifier_ = coreIdentifier; }
2,529,214
./full_match/80001/0x3bbC4Ce3e17e6bDbd25aA142D2537722f63F02b3/sources/project:/contracts/StakingContract.sol
Allows users to select to unstake their tokens during the unstaking phase. Users can only select to unstake when the unstaking phase is active and they have staked tokens. Users can only select to unstake once. This function is called by users when they want to initiate the unstaking process./
function selectUnstake() external { require(isUnstakingPhaseActive, "StakingContract: UnStake Phase is not active yet!"); require(stakedBalances[msg.sender] > 0, "StakingContract: You must have staked tokens to select unstaking"); require(!canUnstake[msg.sender], "StakingContract: Already selected unstaking"); canUnstake[msg.sender] = true; unstakeTimestamp[msg.sender] = block.timestamp; emit UnStakeSelected(msg.sender, block.timestamp); }
5,630,432
pragma solidity ^0.4.11; import "./clock_auction.sol"; /// @title Clock auction modified for sale of pandas /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; // Tracks last 5 sale price of gen0 panda sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; uint256 public constant SurpriseValue = 10 finney; uint256[] CommonPanda; uint256[] RarePanda; uint256 CommonPandaIndex; uint256 RarePandaIndex; // Delegate constructor function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) { CommonPandaIndex = 1; RarePandaIndex = 1; } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), 0 ); _addAuction(_tokenId, auction); } function createGen0Auction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), 1 ); _addAuction(_tokenId, auction); } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId) external payable { // _bid verifies token ID size uint64 isGen0 = tokenIdToAuction[_tokenId].isGen0; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (isGen0 == 1) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function createPanda(uint256 _tokenId,uint256 _type) external { require(msg.sender == address(nonFungibleContract)); if (_type == 0) { CommonPanda.push(_tokenId); }else { RarePanda.push(_tokenId); } } function surprisePanda() external payable { bytes32 bHash = keccak256(block.blockhash(block.number),block.blockhash(block.number-1)); uint256 PandaIndex; if (bHash[25] > 0xC8) { require(uint256(RarePanda.length) >= RarePandaIndex); PandaIndex = RarePandaIndex; RarePandaIndex ++; } else{ require(uint256(CommonPanda.length) >= CommonPandaIndex); PandaIndex = CommonPandaIndex; CommonPandaIndex ++; } _transfer(msg.sender,PandaIndex); } function packageCount() external view returns(uint256 common,uint256 surprise) { common = CommonPanda.length + 1 - CommonPandaIndex; surprise = RarePanda.length + 1 - RarePandaIndex; } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } }
Sanity check that no inputs overflow how many bits we've allocated to store them in the auction struct.
function createGen0Auction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), 1 ); _addAuction(_tokenId, auction); }
12,697,927
./full_match/44787/0x9a7Ad9FBc46535112710f243c3549878Fe828b0f/sources/ToshaFarm_flat.sol
Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (IERC20(TOSHA).totalSupply() >= maxSupply) { return 0; } return _to.sub(_from); }
13,247,267
pragma solidity ^0.4.18; /** * Math operations with safety checks */ contract SafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; simpleAssert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { simpleAssert(b > 0); uint256 c = a / b; simpleAssert(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { simpleAssert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; simpleAssert(c>=a && c>=b); return c; } function simpleAssert(bool assertion) internal pure { if (!assertion) { revert(); } } } contract CFC is SafeMath{ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => uint256) public freezeOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) public { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) public { if (_to == 0x0) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) revert(); if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) revert(); // Check for overflows balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ // 批准另一个地址转币 function approve(address _spender, uint256 _value) public returns (bool success) { if (_value <= 0) revert(); allowance[msg.sender][_spender] = _value; return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (_to == 0x0) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) revert(); if (balanceOf[_from] < _value) revert(); // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) revert(); // Check for overflows if (_value > allowance[_from][msg.sender]) revert(); // Check allowance balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; } // 代币销毁机制,该函数会直接影响区块链中的代币总量 function burn(uint256 _value) public returns (bool success) { if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } function freeze(uint256 _value) public returns (bool success) { if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply emit Freeze(msg.sender, _value); return true; } function unfreeze(uint256 _value) public returns (bool success) { if (freezeOf[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value); emit Unfreeze(msg.sender, _value); return true; } // transfer balance to owner function withdrawEther(uint256 amount) public { if(msg.sender != owner) revert(); owner.transfer(amount); } // can accept ether function() public payable { } }
transfer balance to owner
function withdrawEther(uint256 amount) public { if(msg.sender != owner) revert(); owner.transfer(amount); }
633
// 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/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: contracts/Mines.sol pragma solidity ^0.8.0; interface IGTG { function ownerOf(uint256 id) external view returns (address); function burn(uint256 tokenId) external; function isGoblin(uint16 id) external view returns (bool); function transferFrom( address from, address to, uint256 tokenId ) external; function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) external; } interface IGold { function mint(address account, uint256 amount) external; } interface IGTGGame {} contract Mines is Ownable, IERC721Receiver { bool private _paused = false; uint16 private _randomIndex = 0; uint256 private _randomCalls = 0; mapping(uint256 => address) private _randomSource; struct Stake { uint16 tokenId; uint80 value; address owner; } event TokenStaked(address owner, uint16 tokenId, uint256 value); event VillagersClaimed(uint16 tokenId, uint256 earned, bool unstaked); event GoblinsClaimed(uint16 tokenId, uint256 earned, bool unstaked); IGTG public gtg; IGold public gold; IGTGGame public gtgGame; mapping(uint256 => uint256) public villagerIndices; mapping(address => Stake[]) public villagersStake; mapping(uint256 => uint256) public goblinsIndices; mapping(address => Stake[]) public goblinsStake; address[] public goblinHolders; // Total staked tokens uint256 public totalVillagersStaked; uint256 public totalGoblinsStaked = 0; uint256 public unaccountedRewards = 0; // GoldMiner earn 10000 $GOLD per day uint256 public constant DAILY_GOLD_RATE = 10000 ether; uint256 public constant MINIMUM_TIME_TO_EXIT = 2 days; // uint256 public constant MINIMUM_TIME_TO_EXIT = 0 days; uint256 public constant TAX_PERCENTAGE = 20; uint256 public constant MAXIMUM_GLOBAL_GOLD = 2400000000 ether; uint256 public totalGoldEarned; uint256 public lastClaimTimestamp; uint256 public goblinReward = 0; // emergency rescue to allow unstaking without any checks but without $GOLD bool public rescueEnabled = false; constructor() { // Fill random source addresses _randomSource[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; _randomSource[1] = 0x3cD751E6b0078Be393132286c442345e5DC49699; _randomSource[2] = 0xb5d85CBf7cB3EE0D56b3bB207D5Fc4B82f43F511; _randomSource[3] = 0xC098B2a3Aa256D2140208C3de6543aAEf5cd3A94; _randomSource[4] = 0x28C6c06298d514Db089934071355E5743bf21d60; _randomSource[5] = 0x2FAF487A4414Fe77e2327F0bf4AE2a264a776AD2; _randomSource[6] = 0x267be1C1D684F78cb4F6a176C4911b741E4Ffdc0; } /** CRITICAL TO SETUP */ modifier requireContractsSet() { require( address(gold) != address(0) && address(gtg) != address(0) && address(gtgGame) != address(0), "Contracts not set" ); _; } function setContracts( address _gold, address _gtg, address _gtgGame ) external onlyOwner { gold = IGold(_gold); gtg = IGTG(_gtg); gtgGame = IGTGGame(_gtgGame); } function paused() public view virtual returns (bool) { return _paused; } modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } function getAccountVillagers(address user) external view returns (Stake[] memory) { return villagersStake[user]; } function getAccountGoblins(address user) external view returns (Stake[] memory) { return goblinsStake[user]; } function addTokensToStake(address account, uint16[] calldata tokenIds) external { require( account == msg.sender || msg.sender == address(gtgGame), "You do not have a permission to do that" ); for (uint256 i = 0; i < tokenIds.length; i++) { if (msg.sender != address(gtgGame)) { // dont do this step if its a mint + stake require( gtg.ownerOf(tokenIds[i]) == msg.sender, "This NFT does not belong to address" ); gtg.transferFrom(msg.sender, address(this), tokenIds[i]); } else if (tokenIds[i] == 0) { continue; // there may be gaps in the array for stolen tokens } if (gtg.isGoblin(tokenIds[i])) { _stakeGoblins(account, tokenIds[i]); } else { _stakeVillagers(account, tokenIds[i]); } } } function _stakeVillagers(address account, uint16 tokenId) internal whenNotPaused _updateEarnings { totalVillagersStaked += 1; villagerIndices[tokenId] = villagersStake[account].length; villagersStake[account].push( Stake({ owner: account, tokenId: uint16(tokenId), value: uint80(block.timestamp) }) ); emit TokenStaked(account, tokenId, block.timestamp); } function _stakeGoblins(address account, uint16 tokenId) internal { totalGoblinsStaked += 1; // If account already has some goblins no need to push it to the tracker if (goblinsStake[account].length == 0) { goblinHolders.push(account); } goblinsIndices[tokenId] = goblinsStake[account].length; goblinsStake[account].push( Stake({ owner: account, tokenId: uint16(tokenId), value: uint80(goblinReward) }) ); emit TokenStaked(account, tokenId, goblinReward); } function claimFromStake(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings { uint256 owed = 0; for (uint256 i = 0; i < tokenIds.length; i++) { if (!gtg.isGoblin(tokenIds[i])) { owed += _claimFromVillager(tokenIds[i], unstake); } else { owed += _claimFromGoblin(tokenIds[i], unstake); } } if (owed == 0) return; gold.mint(msg.sender, owed); } function _claimFromVillager(uint16 tokenId, bool unstake) internal returns (uint256 owed) { Stake memory stake = villagersStake[msg.sender][ villagerIndices[tokenId] ]; require( stake.owner == msg.sender, "This NFT does not belong to address" ); require( !(unstake && block.timestamp - stake.value < MINIMUM_TIME_TO_EXIT), "Need to wait 2 days since last claim" ); if (totalGoldEarned < MAXIMUM_GLOBAL_GOLD) { owed = ((block.timestamp - stake.value) * DAILY_GOLD_RATE) / 1 days; } else if (stake.value > lastClaimTimestamp) { owed = 0; // $GOLD production stopped already } else { owed = ((lastClaimTimestamp - stake.value) * DAILY_GOLD_RATE) / 1 days; // stop earning additional $GOLD if it's all been earned } if (unstake) { bool isKilled = false; if (getSomeRandomNumber(tokenId, 100) <= 50) { _payTax(owed); owed = 0; if (getSomeRandomNumber(tokenId, 100) <= 1) { gtg.burn(tokenId); isKilled = true; } } updateRandomIndex(); totalVillagersStaked -= 1; Stake memory lastStake = villagersStake[msg.sender][ villagersStake[msg.sender].length - 1 ]; villagersStake[msg.sender][villagerIndices[tokenId]] = lastStake; villagerIndices[lastStake.tokenId] = villagerIndices[tokenId]; villagersStake[msg.sender].pop(); delete villagerIndices[tokenId]; if (!isKilled) { gtg.safeTransferFrom(address(this), msg.sender, tokenId, ""); } } else { _payTax((owed * TAX_PERCENTAGE) / 100); // Pay some $GOLD to goblins! owed = (owed * (100 - TAX_PERCENTAGE)) / 100; uint80 timestamp = uint80(block.timestamp); villagersStake[msg.sender][villagerIndices[tokenId]] = Stake({ owner: msg.sender, tokenId: uint16(tokenId), value: timestamp }); // reset stake } emit VillagersClaimed(tokenId, owed, unstake); } function _claimFromGoblin(uint16 tokenId, bool unstake) internal returns (uint256 owed) { require( gtg.ownerOf(tokenId) == address(this), "This NFT does not belong to address" ); Stake memory stake = goblinsStake[msg.sender][goblinsIndices[tokenId]]; require( stake.owner == msg.sender, "This NFT does not belong to address" ); owed = (goblinReward - stake.value); if (unstake) { totalGoblinsStaked -= 1; // Remove goblin from total staked Stake memory lastStake = goblinsStake[msg.sender][ goblinsStake[msg.sender].length - 1 ]; goblinsStake[msg.sender][goblinsIndices[tokenId]] = lastStake; goblinsIndices[lastStake.tokenId] = goblinsIndices[tokenId]; goblinsStake[msg.sender].pop(); delete goblinsIndices[tokenId]; updateGoblinAddresses(msg.sender); gtg.safeTransferFrom(address(this), msg.sender, tokenId, ""); } else { goblinsStake[msg.sender][goblinsIndices[tokenId]] = Stake({ owner: msg.sender, tokenId: uint16(tokenId), value: uint80(goblinReward) }); // reset stake } emit GoblinsClaimed(tokenId, owed, unstake); } function updateGoblinAddresses(address account) internal { if (goblinsStake[account].length != 0) { return; // No need to update holders } // Update the address list of holders, account unstaked all goblins address lastOwner = goblinHolders[goblinHolders.length - 1]; uint256 indexOfHolder = 0; for (uint256 i = 0; i < goblinHolders.length; i++) { if (goblinHolders[i] == account) { indexOfHolder = i; break; } } goblinHolders[indexOfHolder] = lastOwner; goblinHolders.pop(); } function rescue(uint16[] calldata tokenIds) external { require(rescueEnabled, "Rescue disabled"); uint16 tokenId; Stake memory stake; for (uint16 i = 0; i < tokenIds.length; i++) { tokenId = tokenIds[i]; if (!gtg.isGoblin(tokenId)) { stake = villagersStake[msg.sender][villagerIndices[tokenId]]; require( stake.owner == msg.sender, "This NFT does not belong to address" ); totalVillagersStaked -= 1; Stake memory lastStake = villagersStake[msg.sender][ villagersStake[msg.sender].length - 1 ]; villagersStake[msg.sender][ villagerIndices[tokenId] ] = lastStake; villagerIndices[lastStake.tokenId] = villagerIndices[tokenId]; villagersStake[msg.sender].pop(); delete villagerIndices[tokenId]; gtg.safeTransferFrom(address(this), msg.sender, tokenId, ""); emit VillagersClaimed(tokenId, 0, true); } else { stake = goblinsStake[msg.sender][goblinsIndices[tokenId]]; require( stake.owner == msg.sender, "This NFT does not belong to address" ); totalGoblinsStaked -= 1; Stake memory lastStake = goblinsStake[msg.sender][ goblinsStake[msg.sender].length - 1 ]; goblinsStake[msg.sender][goblinsIndices[tokenId]] = lastStake; goblinsIndices[lastStake.tokenId] = goblinsIndices[tokenId]; goblinsStake[msg.sender].pop(); delete goblinsIndices[tokenId]; updateGoblinAddresses(msg.sender); gtg.safeTransferFrom(address(this), msg.sender, tokenId, ""); emit GoblinsClaimed(tokenId, 0, true); } } } function _payTax(uint256 _amount) internal { if (totalGoblinsStaked == 0) { unaccountedRewards += _amount; return; } goblinReward += (_amount + unaccountedRewards) / totalGoblinsStaked; unaccountedRewards = 0; } modifier _updateEarnings() { if (totalGoldEarned < MAXIMUM_GLOBAL_GOLD) { totalGoldEarned += ((block.timestamp - lastClaimTimestamp) * totalVillagersStaked * DAILY_GOLD_RATE) / 1 days; lastClaimTimestamp = block.timestamp; } _; } function setRescueEnabled(bool _enabled) external onlyOwner { rescueEnabled = _enabled; } function setPaused(bool _state) external onlyOwner { _paused = _state; } function randomGoblinOwner() external returns (address) { if (totalGoblinsStaked == 0) return address(0x0); uint256 holderIndex = getSomeRandomNumber( totalGoblinsStaked, goblinHolders.length ); updateRandomIndex(); return goblinHolders[holderIndex]; } function updateRandomIndex() internal { _randomIndex += 1; _randomCalls += 1; if (_randomIndex > 6) _randomIndex = 0; } function getSomeRandomNumber(uint256 _seed, uint256 _limit) internal view returns (uint16) { uint256 extra = 0; for (uint16 i = 0; i < 7; i++) { extra += _randomSource[_randomIndex].balance; } uint256 random = uint256( keccak256( abi.encodePacked( _seed, blockhash(block.number - 1), block.coinbase, block.difficulty, msg.sender, extra, _randomCalls, _randomIndex ) ) ); return uint16(random % _limit); } function changeRandomSource(uint256 _id, address _address) external onlyOwner { _randomSource[_id] = _address; } function shuffleSeeds(uint256 _seed, uint256 _max) external onlyOwner { uint256 shuffleCount = getSomeRandomNumber(_seed, _max); _randomIndex = uint16(shuffleCount); for (uint256 i = 0; i < shuffleCount; i++) { updateRandomIndex(); } } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require( from == address(0x0), "Cannot send tokens to this contact directly" ); return IERC721Receiver.onERC721Received.selector; } }
File: contracts/Mines.sol
interface IGTG { function ownerOf(uint256 id) external view returns (address); function burn(uint256 tokenId) external; function isGoblin(uint16 id) external view returns (bool); function transferFrom( address from, address to, uint256 tokenId ) external; function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) external; }
9,924,280
./full_match/1/0xc10cF90e627434569fd26c8756B27D4aF20296E6/sources/src/minter/DNAMinter.sol
Set the Cre8orsNFT contract address. This function can only be called by an admin, identified by the "cre8orsNFT" contract address. _dnaNft The new address of the DNA contract to be set.
function setDnaNFT(address _dnaNft) public onlyAdmin(dnaNft) { dnaNft = _dnaNft; }
3,854,396
./full_match/80001/0x799022f326F50e330dCf5cFEbCEeC8356CD0aFa1/sources/contracts/IndradexBaseVault.sol
Returns the current withdrawalTime./
function getWithdrawalTime() external view returns (uint256) { return _withdrawalTime; }
861,914
./partial_match/100/0x3E8231c631E7Edf9F2Bd153d2B43c64b7D330cca/sources/PriceBettingUserRecord.sol
userAddr -> bets: cleared or not
function getBetterBets(address user, uint256 period, uint256 idxStart, uint256 outLength, uint256 option) public view returns (IPriceBetting.Bet[] memory betsOut, uint256 cidx3, uint256 uidx3, uint256 idxStart3, uint256 idxLast3) { (uint256[] memory indexes, uint256 cidx2, uint256 uidx2, uint256 idxStart2, uint256 idxLast2) = getBetIndexes(user, period, idxStart, outLength, option); cidx3 = cidx2; uidx3 = uidx2; idxStart3 = idxStart2; idxLast3 = idxLast2; IPriceBetting PriceBetting = IPriceBetting(addrPriceBetting); betsOut = new IPriceBetting.Bet[](indexes.length); if (period == 60) { for (uint i = 0; i < indexes.length; i++) { betsOut[i] = PriceBetting.bets60(indexes[i]); } for (uint i = 0; i < indexes.length; i++) { betsOut[i] = PriceBetting.bets300(indexes[i]); } } }
16,645,851
pragma solidity ^0.4.24; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract ArrayTools { function _combineArray(uint256[] _array) internal pure returns(uint256) { uint256 fullAmount; for(uint256 i = 0; i < _array.length; i++) { require(_array[i] > 0); fullAmount += _array[i]; } return fullAmount; } } contract IQDAO { function balanceOf(address _owner) public view returns (uint256); function approveForOtherContracts(address _sender, address _spender, uint256 _value) external; function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract WhitelistMigratable is Ownable { mapping(address => bool) public governanceContracts; event GovernanceContractAdded(address addr); event GovernanceContractRemoved(address addr); modifier onlyGovernanceContracts() { require(governanceContracts[msg.sender]); _; } function addAddressToGovernanceContract(address addr) onlyOwner public returns(bool success) { if (!governanceContracts[addr]) { governanceContracts[addr] = true; emit GovernanceContractAdded(addr); success = true; } } function removeAddressFromGovernanceContract(address addr) onlyOwner public returns(bool success) { if (governanceContracts[addr]) { governanceContracts[addr] = false; emit GovernanceContractRemoved(addr); success = true; } } } contract SafeStorage is WhitelistMigratable, ArrayTools { using SafeMath for uint256; event LockSlotCreated(address indexed holder, uint256 id, uint256 amount); struct LockSlot{ uint256[] tokens; uint256[] periods; uint256 paidTokens; bool finalized; } mapping (address => mapping(uint256 => LockSlot)) internal lockTokenStorage; mapping (address => uint256[]) private lockSlotIdList; address[] internal holdersList; address[] internal totalSlot; uint256 public maximumDurationToFreeze; uint256 public lostTime; uint256 public totalLockedTokens; IQDAO public token_; /** * @dev Create slot for holder * Usage of this method only owner * @param _holder address The address which you want to lock tokens * @param _tokens uint256[] the amount of tokens to be locked * @param _periods uint256[] the amount of periods to be locked */ function createLockSlot(address _holder, uint256[] _tokens, uint256[] _periods) public onlyGovernanceContracts { require(_holder != address(0), "LockStorage cannot be created for this address"); require (_tokens.length == _periods.length && _tokens.length > 0); require(_combineArray(_periods) <= maximumDurationToFreeze, "Incorrect time, should be less 3 years"); require(_combineArray(_tokens) > 0, "Incorrect amount"); uint256 fullAmount = _combineArray(_tokens); uint256 newId = totalSlot.length; token_.approveForOtherContracts(msg.sender, this, fullAmount); token_.transferFrom(msg.sender, this, fullAmount); lockTokenStorage[_holder][newId] = _createLockSlot(_tokens, _periods); totalSlot.push(_holder); totalLockedTokens = totalLockedTokens.add(fullAmount); if(lockSlotIdList[_holder].length == 0) { holdersList.push(_holder); } lockSlotIdList[_holder].push(newId); emit LockSlotCreated(_holder, newId, fullAmount); } /** * @dev Returned holder's address * @param _lockSlotId uint256 unique id lockSlot */ function getAddressToId(uint256 _lockSlotId) public view returns(address) { return totalSlot[_lockSlotId]; } /** * @dev Returned all created unique ids * @param _holder address The holder's address */ function getAllLockSlotIdsToAddress(address _holder) public view returns(uint256[] _lockSlotIds) { return lockSlotIdList[_holder]; } function _createLockSlot(uint256[] _lockTokens, uint256[] _lockPeriods) internal view returns(LockSlot memory _lockSlot) { _lockPeriods[0] +=now; if (_lockPeriods.length > 1) { for(uint256 i = 1; i < _lockPeriods.length; i++) { _lockPeriods[i] += _lockPeriods[i-1]; } } _lockSlot = LockSlot({ tokens: _lockTokens, periods: _lockPeriods, paidTokens: 0, finalized: false }); } } contract ReleaseLockToken is SafeStorage { event TokensWithdrawed(address indexed sender, uint256 amount, uint256 time); uint256 public withdrawableTokens; /** * @dev Withdraw locked tokens * Usage of this method only holder this lockSlot's id * @param _lockSlotId uint256 unique id lockSlot */ function release(uint256 _lockSlotId) public { require(_validateWithdraw(msg.sender, _lockSlotId)); uint256 tokensForWithdraw = _getAvailableTokens(msg.sender, _lockSlotId); lockTokenStorage[msg.sender][_lockSlotId].paidTokens = lockTokenStorage[msg.sender][_lockSlotId].paidTokens.add(tokensForWithdraw); token_.transfer(msg.sender, tokensForWithdraw); if(_combineArray(lockTokenStorage[msg.sender][_lockSlotId].tokens) == lockTokenStorage[msg.sender][_lockSlotId].paidTokens) { _finalizeLock(msg.sender, _lockSlotId); } withdrawableTokens = withdrawableTokens.add(tokensForWithdraw); totalLockedTokens = totalLockedTokens.sub(tokensForWithdraw); emit TokensWithdrawed(msg.sender, tokensForWithdraw, now); } /** * @dev Returned all withdrawn tokens */ function getWithdrawableTokens() public view returns(uint256) { return withdrawableTokens; } /** * @dev Withdrawn lost tokens * Usage of this method only owner * @param _lockSlotId uint256 unique id lockSlot */ function withdrawLostToken(uint256 _lockSlotId) public onlyGovernanceContracts { require(now > lostTime.add( lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].periods[lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].periods.length-1]), "Tokens are not lost"); uint256 tokensForWithdraw = _getAvailableTokens(getAddressToId(_lockSlotId), _lockSlotId); withdrawableTokens = withdrawableTokens.add(tokensForWithdraw); totalLockedTokens = totalLockedTokens.sub(tokensForWithdraw); lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].paidTokens = _combineArray(lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].tokens); _finalizeLock(getAddressToId(_lockSlotId), _lockSlotId); token_.transfer( owner, tokensForWithdraw); } /** * @dev Returned date and amount to counter * @param _lockSlotId uint256 unique id lockSlot * @param _i uint256 count number */ function getDateAndReleaseToCounter(uint256 _lockSlotId, uint256 _i) public view returns(uint256 _nextDate, uint256 _nextRelease) { require( _i < lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].periods.length); _nextRelease = lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].tokens[_i]; _nextDate = lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].periods[_i]; } /** * @dev Returned nearest date for withdraw * @param _lockSlotId uint256 unique id lockSlot */ function getNextDateWithdraw(uint256 _lockSlotId) public view returns(uint256) { uint256 nextDate; if(now > lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].periods[lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].periods.length-1]) { nextDate = 0; } else { for(uint256 i = 0; i < lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].periods.length; i++) { if(now < lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].periods[i]) { nextDate = lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].periods[i]; break; } } } return nextDate; } function _finalizeLock(address _who, uint256 _id) internal { lockTokenStorage[_who][_id].finalized = true; } function _validateWithdraw(address _who, uint256 _id) internal view returns(bool) { require(!lockTokenStorage[_who][_id].finalized, "Full withdraw already exists"); require(_combineArray(lockTokenStorage[_who][_id].tokens) > 0 , "This lockStorage is not exists"); require(now > lockTokenStorage[_who][_id].periods[0], "Unlock time has not come"); return true; } function _getAvailableTokens(address _who, uint256 _id) internal view returns(uint256) { uint256 tokensForWithdraw; uint256 paidTokens = lockTokenStorage[_who][_id].paidTokens; for(uint256 i = lockTokenStorage[_who][_id].periods.length-1; i >= 0; i--) { if(now >= lockTokenStorage[_who][_id].periods[i]) { for(uint256 y = 0; y < i+1; y++) { tokensForWithdraw += lockTokenStorage[_who][_id].tokens[y]; } tokensForWithdraw -= paidTokens; break; } } return tokensForWithdraw; } } contract TimeLockedTokenStorage is ReleaseLockToken { constructor(address _token) public { token_ = IQDAO(_token); lostTime = 7862400; // 3 months maximumDurationToFreeze = 94694400; // 3 years } /** * @dev Returned available tokens for withdraw * @param _lockSlotId uint256 unique id lockSlot */ function getAvailableTokens(uint256 _lockSlotId) public view returns(uint256) { if (now < uint256(lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].periods[0])) { return 0; } else { return _getAvailableTokens(getAddressToId(_lockSlotId), _lockSlotId); } } /** * @dev Returned total holders */ function getHoldersQuantity() public view returns(uint256) { return holdersList.length; } /** * @dev Returned total locked slots */ function getSlotsQuantity() public view returns(uint256) { return totalSlot.length; } /** * @dev Returned total locked tokens */ function getTotalLockedTokens() public view returns(uint256) { return totalLockedTokens; } /** * @dev Returned params for lockSlot * @param _lockSlotId uint256 unique id lockSlot */ function getLock(uint256 _lockSlotId) public view returns( uint256 _amountTokens, uint256[] _periods, uint256[] _tokens, uint256 _paidTokens, bool _finalize) { _amountTokens = _combineArray(lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].tokens); _periods = lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].periods; _tokens = lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].tokens; _paidTokens = lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].paidTokens; _finalize = lockTokenStorage[getAddressToId(_lockSlotId)][_lockSlotId].finalized; } }
Returned total holders/
function getHoldersQuantity() public view returns(uint256) { return holdersList.length; }
945,744
./full_match/80001/0xc9304257B62C12a31763a3DC945896fb78a0F34D/sources/contracts/extension/DropSinglePhase.sol
Logic borrowed From https://thirdweb.com/nach.eth/DynamicFreeMint thanks to Nacho Iacovino number for updating the numClaimedForFree
function _getTotalPrice( uint256 _quantityToClaim, uint256 _quantityForFree, bool _isActiveOverride, uint256 _pricePerToken, uint256 _printPriceTotal ) internal virtual returns (uint256 totalPrice) { if (_isActiveOverride) { uint256 freeClaimed = numClaimedForFree[_dropMsgSender()]; uint256 freeAllowance = (_quantityForFree > 0) && (_quantityForFree > freeClaimed) ? _quantityForFree - numClaimedForFree[_dropMsgSender()] : 0; uint256 freeQuantity = _quantityToClaim > freeAllowance ? freeAllowance : _quantityToClaim; uint256 paidQuantity = _quantityToClaim > freeQuantity ? (_quantityToClaim - freeQuantity) : 0; uint256 subtotalPrice = paidQuantity * _pricePerToken; totalPrice = subtotalPrice + _printPriceTotal; uint256 updatedClaimForFree = paidQuantity > 0 ? freeQuantity : _quantityToClaim; numClaimedForFree[_dropMsgSender()] += updatedClaimForFree; totalPrice = _quantityToClaim * _pricePerToken; } return totalPrice; }
839,940
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY267() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF771(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER36(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE520(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE275(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER513(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL255(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD260(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB684(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB684(a, b, "SafeMath: subtraction overflow"); } function SUB684(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 MUL872(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 DIV551(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV551(a, b, "SafeMath: division by zero"); } function DIV551(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 MOD699(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD699(a, b, "SafeMath: modulo by zero"); } function MOD699(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT292(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function SENDVALUE986(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL437(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL437(target, data, "Address: low-level call failed"); } function FUNCTIONCALL437(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE654(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE142(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE654(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE654(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT292(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER627(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFER36.selector, to, value)); } function SAFETRANSFERFROM565(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFERFROM54.selector, from, to, value)); } function SAFEAPPROVE47(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE520(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, value)); } function SAFEINCREASEALLOWANCE824(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE520(address(this), spender).ADD260(value); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE914(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE520(address(this), spender).SUB684(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN808(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).FUNCTIONCALL437(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface IMultiVaultStrategy { function WANT777() external view returns (address); //inject NONSTANDARD NAMING function DEPOSIT294() external; //inject NONSTANDARD NAMING function WITHDRAW808(address _asset) external; //inject NONSTANDARD NAMING function WITHDRAW808(uint _amount) external returns (uint); //inject NONSTANDARD NAMING function WITHDRAWTOCONTROLLER653(uint _amount) external; //inject NONSTANDARD NAMING function SKIM294() external; //inject NONSTANDARD NAMING function HARVEST506(address _mergedStrategy) external; //inject NONSTANDARD NAMING function WITHDRAWALL927() external returns (uint); //inject NONSTANDARD NAMING function BALANCEOF771() external view returns (uint); //inject NONSTANDARD NAMING function WITHDRAWFEE692(uint) external view returns (uint); // pJar: 0.5% (50/10000) //inject NONSTANDARD NAMING } interface IValueMultiVault { function CAP418() external view returns (uint); //inject NONSTANDARD NAMING function GETCONVERTER215(address _want) external view returns (address); //inject NONSTANDARD NAMING function GETVAULTMASTER236() external view returns (address); //inject NONSTANDARD NAMING function BALANCE180() external view returns (uint); //inject NONSTANDARD NAMING function TOKEN385() external view returns (address); //inject NONSTANDARD NAMING function AVAILABLE930(address _want) external view returns (uint); //inject NONSTANDARD NAMING function ACCEPT281(address _input) external view returns (bool); //inject NONSTANDARD NAMING function CLAIMINSURANCE45() external; //inject NONSTANDARD NAMING function EARN427(address _want) external; //inject NONSTANDARD NAMING function HARVEST506(address reserve, uint amount) external; //inject NONSTANDARD NAMING function WITHDRAW_FEE118(uint _shares) external view returns (uint); //inject NONSTANDARD NAMING function CALC_TOKEN_AMOUNT_DEPOSIT453(uint[] calldata _amounts) external view returns (uint); //inject NONSTANDARD NAMING function CALC_TOKEN_AMOUNT_WITHDRAW2(uint _shares, address _output) external view returns (uint); //inject NONSTANDARD NAMING function CONVERT_RATE825(address _input, uint _amount) external view returns (uint); //inject NONSTANDARD NAMING function GETPRICEPERFULLSHARE124() external view returns (uint); //inject NONSTANDARD NAMING function GET_VIRTUAL_PRICE769() external view returns (uint); // average dollar value of vault share token //inject NONSTANDARD NAMING function DEPOSIT294(address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITFOR247(address _account, address _to, address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITALL52(uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITALLFOR442(address _account, address _to, uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function WITHDRAW808(uint _shares, address _output, uint _min_output_amount) external returns (uint); //inject NONSTANDARD NAMING function WITHDRAWFOR513(address _account, uint _shares, address _output, uint _min_output_amount) external returns (uint _output_amount); //inject NONSTANDARD NAMING function HARVESTSTRATEGY825(address _strategy) external; //inject NONSTANDARD NAMING function HARVESTWANT168(address _want) external; //inject NONSTANDARD NAMING function HARVESTALLSTRATEGIES334() external; //inject NONSTANDARD NAMING } interface IShareConverter { function CONVERT_SHARES_RATE463(address _input, address _output, uint _inputAmount) external view returns (uint _outputAmount); //inject NONSTANDARD NAMING function CONVERT_SHARES33(address _input, address _output, uint _inputAmount) external returns (uint _outputAmount); //inject NONSTANDARD NAMING } interface Converter { function CONVERT349(address) external returns (uint); //inject NONSTANDARD NAMING } contract MultiStablesVaultController { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; address public strategist; struct StrategyInfo { address strategy; uint quota; // set = 0 to disable uint percent; } IValueMultiVault public vault; address public basedWant; address[] public wantTokens; // sorted by preference // want => quota, length mapping(address => uint) public wantQuota; mapping(address => uint) public wantStrategyLength; // want => stratId => StrategyInfo mapping(address => mapping(uint => StrategyInfo)) public strategies; mapping(address => mapping(address => bool)) public approvedStrategies; mapping(address => bool) public investDisabled; IShareConverter public shareConverter; // converter for shares (3CRV <-> BCrv, etc ...) address public lazySelectedBestStrategy; // we pre-set the best strategy to avoid gas cost of iterating the array constructor(IValueMultiVault _vault) public { require(address(_vault) != address(0), "!_vault"); vault = _vault; basedWant = vault.TOKEN385(); governance = msg.sender; strategist = msg.sender; } function SETGOVERNANCE701(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETSTRATEGIST330(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategist = _strategist; } function APPROVESTRATEGY673(address _want, address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); approvedStrategies[_want][_strategy] = true; } function REVOKESTRATEGY92(address _want, address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); approvedStrategies[_want][_strategy] = false; } function SETWANTQUOTA716(address _want, uint _quota) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); wantQuota[_want] = _quota; } function SETWANTSTRATEGYLENGTH858(address _want, uint _length) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); wantStrategyLength[_want] = _length; } // want => stratId => StrategyInfo function SETSTRATEGYINFO462(address _want, uint _sid, address _strategy, uint _quota, uint _percent) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); require(approvedStrategies[_want][_strategy], "!approved"); strategies[_want][_sid].strategy = _strategy; strategies[_want][_sid].quota = _quota; strategies[_want][_sid].percent = _percent; } function SETSHARECONVERTER560(IShareConverter _shareConverter) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); shareConverter = _shareConverter; } function SETINVESTDISABLED819(address _want, bool _investDisabled) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); investDisabled[_want] = _investDisabled; } function SETWANTTOKENS997(address[] memory _wantTokens) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); delete wantTokens; uint _wlength = _wantTokens.length; for (uint i = 0; i < _wlength; ++i) { wantTokens.push(_wantTokens[i]); } } function GETSTRATEGYCOUNT337() external view returns(uint _strategyCount) { //inject NONSTANDARD NAMING _strategyCount = 0; uint _wlength = wantTokens.length; for (uint i = 0; i < _wlength; i++) { _strategyCount = _strategyCount.ADD260(wantStrategyLength[wantTokens[i]]); } } function WANTLENGTH873() external view returns (uint) { //inject NONSTANDARD NAMING return wantTokens.length; } function WANTSTRATEGYBALANCE73(address _want) public view returns (uint) { //inject NONSTANDARD NAMING uint _bal = 0; for (uint _sid = 0; _sid < wantStrategyLength[_want]; _sid++) { _bal = _bal.ADD260(IMultiVaultStrategy(strategies[_want][_sid].strategy).BALANCEOF771()); } return _bal; } function WANT777() external view returns (address) { //inject NONSTANDARD NAMING if (lazySelectedBestStrategy != address(0)) { return IMultiVaultStrategy(lazySelectedBestStrategy).WANT777(); } uint _wlength = wantTokens.length; if (_wlength > 0) { if (_wlength == 1) { return wantTokens[0]; } for (uint i = 0; i < _wlength; i++) { address _want = wantTokens[i]; uint _bal = WANTSTRATEGYBALANCE73(_want); if (_bal < wantQuota[_want]) { return _want; } } } return basedWant; } function SETLAZYSELECTEDBESTSTRATEGY629(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); lazySelectedBestStrategy = _strategy; } function GETBESTSTRATEGY227(address _want) public view returns (address _strategy) { //inject NONSTANDARD NAMING if (lazySelectedBestStrategy != address(0) && IMultiVaultStrategy(lazySelectedBestStrategy).WANT777() == _want) { return lazySelectedBestStrategy; } uint _wantStrategyLength = wantStrategyLength[_want]; _strategy = address(0); if (_wantStrategyLength == 0) return _strategy; uint _totalBal = WANTSTRATEGYBALANCE73(_want); if (_totalBal == 0) { // first depositor, simply return the first strategy return strategies[_want][0].strategy; } uint _bestDiff = 201; for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; uint _stratBal = IMultiVaultStrategy(sinfo.strategy).BALANCEOF771(); if (_stratBal < sinfo.quota) { uint _diff = _stratBal.ADD260(_totalBal).MUL872(100).DIV551(_totalBal).SUB684(sinfo.percent); // [100, 200] - [percent] if (_diff < _bestDiff) { _bestDiff = _diff; _strategy = sinfo.strategy; } } } if (_strategy == address(0)) { _strategy = strategies[_want][0].strategy; } } function EARN427(address _token, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist"); address _strategy = GETBESTSTRATEGY227(_token); if (_strategy == address(0) || IMultiVaultStrategy(_strategy).WANT777() != _token) { // forward to vault and then call earnExtra() by its governance IERC20(_token).SAFETRANSFER627(address(vault), _amount); } else { IERC20(_token).SAFETRANSFER627(_strategy, _amount); IMultiVaultStrategy(_strategy).DEPOSIT294(); } } function WITHDRAW_FEE118(address _want, uint _amount) external view returns (uint) { //inject NONSTANDARD NAMING address _strategy = GETBESTSTRATEGY227(_want); return (_strategy == address(0)) ? 0 : IMultiVaultStrategy(_strategy).WITHDRAWFEE692(_amount); } function BALANCEOF771(address _want, bool _sell) external view returns (uint _totalBal) { //inject NONSTANDARD NAMING uint _wlength = wantTokens.length; if (_wlength == 0) { return 0; } _totalBal = 0; for (uint i = 0; i < _wlength; i++) { address wt = wantTokens[i]; uint _bal = WANTSTRATEGYBALANCE73(wt); if (wt != _want) { _bal = shareConverter.CONVERT_SHARES_RATE463(wt, _want, _bal); if (_sell) { _bal = _bal.MUL872(9998).DIV551(10000); // minus 0.02% for selling } } _totalBal = _totalBal.ADD260(_bal); } } function WITHDRAWALL927(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); // WithdrawAll sends 'want' to 'vault' IMultiVaultStrategy(_strategy).WITHDRAWALL927(); } function INCASETOKENSGETSTUCK116(address _token, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); IERC20(_token).SAFETRANSFER627(address(vault), _amount); } function INCASESTRATEGYGETSTUCK927(address _strategy, address _token) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); IMultiVaultStrategy(_strategy).WITHDRAW808(_token); IERC20(_token).SAFETRANSFER627(address(vault), IERC20(_token).BALANCEOF771(address(this))); } function CLAIMINSURANCE45() external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); vault.CLAIMINSURANCE45(); } // note that some strategies do not allow controller to harvest function HARVESTSTRATEGY825(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); IMultiVaultStrategy(_strategy).HARVEST506(address(0)); } function HARVESTWANT168(address _want) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); uint _wantStrategyLength = wantStrategyLength[_want]; address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; if (_firstStrategy == address(0)) { _firstStrategy = sinfo.strategy; } else { IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy); } } if (_firstStrategy != address(0)) { IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0)); } } function HARVESTALLSTRATEGIES334() external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); uint _wlength = wantTokens.length; address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here for (uint i = 0; i < _wlength; i++) { address _want = wantTokens[i]; uint _wantStrategyLength = wantStrategyLength[_want]; for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; if (_firstStrategy == address(0)) { _firstStrategy = sinfo.strategy; } else { IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy); } } } if (_firstStrategy != address(0)) { IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0)); } } function SWITCHFUND172(IMultiVaultStrategy _srcStrat, IMultiVaultStrategy _destStrat, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); _srcStrat.WITHDRAWTOCONTROLLER653(_amount); address _srcWant = _srcStrat.WANT777(); address _destWant = _destStrat.WANT777(); if (_srcWant != _destWant) { _amount = IERC20(_srcWant).BALANCEOF771(address(this)); require(shareConverter.CONVERT_SHARES_RATE463(_srcWant, _destWant, _amount) > 0, "rate=0"); IERC20(_srcWant).SAFETRANSFER627(address(shareConverter), _amount); shareConverter.CONVERT_SHARES33(_srcWant, _destWant, _amount); } IERC20(_destWant).SAFETRANSFER627(address(_destStrat), IERC20(_destWant).BALANCEOF771(address(this))); _destStrat.DEPOSIT294(); } function WITHDRAW808(address _want, uint _amount) external returns (uint _withdrawFee) { //inject NONSTANDARD NAMING require(msg.sender == address(vault), "!vault"); _withdrawFee = 0; uint _toWithdraw = _amount; uint _wantStrategyLength = wantStrategyLength[_want]; uint _received; for (uint _sid = _wantStrategyLength; _sid > 0; _sid--) { StrategyInfo storage sinfo = strategies[_want][_sid - 1]; IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy); uint _stratBal = _strategy.BALANCEOF771(); if (_toWithdraw < _stratBal) { _received = _strategy.WITHDRAW808(_toWithdraw); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received)); return _withdrawFee; } _received = _strategy.WITHDRAWALL927(); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received)); if (_received >= _toWithdraw) { return _withdrawFee; } _toWithdraw = _toWithdraw.SUB684(_received); } if (_toWithdraw > 0) { // still not enough, try to withdraw from other wants strategies uint _wlength = wantTokens.length; for (uint i = _wlength; i > 0; i--) { address wt = wantTokens[i - 1]; if (wt != _want) { (uint _wamt, uint _wdfee) = _WITHDRAWOTHERWANT971(_want, wt, _toWithdraw); _withdrawFee = _withdrawFee.ADD260(_wdfee); if (_wamt >= _toWithdraw) { return _withdrawFee; } _toWithdraw = _toWithdraw.SUB684(_wamt); } } } return _withdrawFee; } function _WITHDRAWOTHERWANT971(address _want, address _other, uint _amount) internal returns (uint _wantAmount, uint _withdrawFee) { //inject NONSTANDARD NAMING // Check balance uint b = IERC20(_want).BALANCEOF771(address(this)); _withdrawFee = 0; if (b >= _amount) { _wantAmount = b; } else { uint _toWithdraw = _amount.SUB684(b); uint _toWithdrawOther = _toWithdraw.MUL872(101).DIV551(100); // add 1% extra uint _otherBal = IERC20(_other).BALANCEOF771(address(this)); if (_otherBal < _toWithdrawOther) { uint _otherStrategyLength = wantStrategyLength[_other]; for (uint _sid = _otherStrategyLength; _sid > 0; _sid--) { StrategyInfo storage sinfo = strategies[_other][_sid - 1]; IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy); uint _stratBal = _strategy.BALANCEOF771(); uint _needed = _toWithdrawOther.SUB684(_otherBal); uint _wdamt = (_needed < _stratBal) ? _needed : _stratBal; _strategy.WITHDRAWTOCONTROLLER653(_wdamt); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_wdamt)); _otherBal = IERC20(_other).BALANCEOF771(address(this)); if (_otherBal >= _toWithdrawOther) { break; } } } IERC20(_other).SAFETRANSFER627(address(shareConverter), _otherBal); shareConverter.CONVERT_SHARES33(_other, _want, _otherBal); _wantAmount = IERC20(_want).BALANCEOF771(address(this)); } IERC20(_want).SAFETRANSFER627(address(vault), _wantAmount); } }
inject NONSTANDARD NAMING
function MOD699(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
13,085,313
./full_match/1/0x904332C09e2161539cd819dA42ac4fe70e3e97d0/sources/contracts/bt.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("BOBATEA", "BT") { 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 = 20; uint256 _buyLiquidityFee = 5; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 30; uint256 _sellLiquidityFee = 10; uint256 _sellDevFee = 0; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 0; uint256 totalSupply = 1 * 1e6 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; 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);
2,993,836
/** *Submitted for verification at Etherscan.io on 2022-02-16 */ // SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; abstract contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } modifier onlyOwner() { require(owner == msg.sender, 'NOT_OWNER'); _; } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), 'ZERO_ADDR'); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) private _uintStorage; mapping(bytes32 => string) private _stringStorage; mapping(bytes32 => address) private _addressStorage; mapping(bytes32 => bytes) private _bytesStorage; mapping(bytes32 => bool) private _boolStorage; mapping(bytes32 => int256) private _intStorage; // *** Getter Methods *** function getUint(bytes32 key) public view returns (uint256) { return _uintStorage[key]; } function getString(bytes32 key) public view returns (string memory) { return _stringStorage[key]; } function getAddress(bytes32 key) public view returns (address) { return _addressStorage[key]; } function getBytes(bytes32 key) public view returns (bytes memory) { return _bytesStorage[key]; } function getBool(bytes32 key) public view returns (bool) { return _boolStorage[key]; } function getInt(bytes32 key) public view returns (int256) { return _intStorage[key]; } // *** Setter Methods *** function _setUint(bytes32 key, uint256 value) internal { _uintStorage[key] = value; } function _setString(bytes32 key, string memory value) internal { _stringStorage[key] = value; } function _setAddress(bytes32 key, address value) internal { _addressStorage[key] = value; } function _setBytes(bytes32 key, bytes memory value) internal { _bytesStorage[key] = value; } function _setBool(bytes32 key, bool value) internal { _boolStorage[key] = value; } function _setInt(bytes32 key, int256 value) internal { _intStorage[key] = value; } // *** Delete Methods *** function _deleteUint(bytes32 key) internal { delete _uintStorage[key]; } function _deleteString(bytes32 key) internal { delete _stringStorage[key]; } function _deleteAddress(bytes32 key) internal { delete _addressStorage[key]; } function _deleteBytes(bytes32 key) internal { delete _bytesStorage[key]; } function _deleteBool(bytes32 key) internal { delete _boolStorage[key]; } function _deleteInt(bytes32 key) internal { delete _intStorage[key]; } } contract Burner { constructor(address tokenAddress, bytes32 salt) { BurnableMintableCappedERC20(tokenAddress).burn(salt); selfdestruct(payable(address(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); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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 { mapping(address => uint256) public override balanceOf; mapping(address => mapping(address => uint256)) public override allowance; uint256 public override totalSupply; string public name; string public symbol; uint8 public immutable decimals; /** * @dev Sets the values for {name}, {symbol}, and {decimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) { name = name_; symbol = symbol_; decimals = decimals_; } /** * @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-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(), allowance[sender][_msgSender()] - 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, allowance[_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) { _approve(_msgSender(), spender, allowance[_msgSender()][spender] - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), 'ZERO_ADDR'); require(recipient != address(0), 'ZERO_ADDR'); _beforeTokenTransfer(sender, recipient, amount); balanceOf[sender] -= amount; balanceOf[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ZERO_ADDR'); _beforeTokenTransfer(address(0), account, amount); totalSupply += amount; balanceOf[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ZERO_ADDR'); _beforeTokenTransfer(account, address(0), amount); balanceOf[account] -= amount; totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), 'ZERO_ADDR'); require(spender != address(0), 'ZERO_ADDR'); allowance[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 BurnableMintableCappedERC20 is ERC20, Ownable { uint256 public cap; bytes32 private constant PREFIX_TOKEN_FROZEN = keccak256('token-frozen'); bytes32 private constant KEY_ALL_TOKENS_FROZEN = keccak256('all-tokens-frozen'); event Frozen(address indexed owner); event Unfrozen(address indexed owner); constructor( string memory name, string memory symbol, uint8 decimals, uint256 capacity ) ERC20(name, symbol, decimals) Ownable() { cap = capacity; } function depositAddress(bytes32 salt) public view returns (address) { // This would be easier, cheaper, simpler, and result in globally consistent deposit addresses for any salt (all chains, all tokens). // return address(uint160(uint256(keccak256(abi.encodePacked(bytes32(0x000000000000000000000000000000000000000000000000000000000000dead), salt))))); /* Convert a hash which is bytes32 to an address which is 20-byte long according to https://docs.soliditylang.org/en/v0.8.1/control-structures.html?highlight=create2#salted-contract-creations-create2 */ return address( uint160( uint256( keccak256( abi.encodePacked( bytes1(0xff), owner, salt, keccak256(abi.encodePacked(type(Burner).creationCode, abi.encode(address(this)), salt)) ) ) ) ) ); } function mint(address account, uint256 amount) public onlyOwner { uint256 capacity = cap; require(capacity == 0 || totalSupply + amount <= capacity, 'CAP_EXCEEDED'); _mint(account, amount); } function burn(bytes32 salt) public onlyOwner { address account = depositAddress(salt); _burn(account, balanceOf[account]); } function _beforeTokenTransfer( address, address, uint256 ) internal view override { require(!EternalStorage(owner).getBool(KEY_ALL_TOKENS_FROZEN), 'IS_FROZEN'); require(!EternalStorage(owner).getBool(keccak256(abi.encodePacked(PREFIX_TOKEN_FROZEN, symbol))), 'IS_FROZEN'); } }
This would be easier, cheaper, simpler, and result in globally consistent deposit addresses for any salt (all chains, all tokens). return address(uint160(uint256(keccak256(abi.encodePacked(bytes32(0x000000000000000000000000000000000000000000000000000000000000dead), salt)))));
function depositAddress(bytes32 salt) public view returns (address) { return address( uint160( uint256( keccak256( abi.encodePacked( bytes1(0xff), owner, salt, keccak256(abi.encodePacked(type(Burner).creationCode, abi.encode(address(this)), salt)) ) ) ) ) );
10,644,685
pragma solidity 0.5.17; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {DepositStates} from "./DepositStates.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; library DepositLiquidation { using BTCUtils for bytes; using BytesLib for bytes; using SafeMath for uint256; using SafeMath for uint64; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Notifies the keep contract of fraud. /// @dev Calls out to the keep contract. this could get expensive if preimage is large. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. /// @return True if fraud, otherwise revert. function submitSignatureFraud( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public returns (bool _isFraud) { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); return _keep.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage); } /// @notice Determines the collateralization percentage of the signing group. /// @dev Compares the bond value and lot value. /// @param _d Deposit storage pointer. /// @return Collateralization percentage as uint. function getCollateralizationPercentage(DepositUtils.Deposit storage _d) public view returns (uint256) { // Determine value of the lot in wei uint256 _satoshiPrice = _d.fetchBitcoinPrice(); uint64 _lotSizeSatoshis = _d.lotSizeSatoshis; uint256 _lotValue = _lotSizeSatoshis.mul(_satoshiPrice); // Amount of wei the signers have uint256 _bondValue = _d.fetchBondAmount(); // This converts into a percentage return (_bondValue.mul(100).div(_lotValue)); } /// @dev Starts signer liquidation by seizing signer bonds. /// If the deposit is currently being redeemed, the redeemer /// receives the full bond value; otherwise, a falling price auction /// begins to buy 1 TBTC in exchange for a portion of the seized bonds; /// see purchaseSignerBondsAtAuction(). /// @param _wasFraud True if liquidation is being started due to fraud, false if for any other reason. /// @param _d Deposit storage pointer. function startLiquidation(DepositUtils.Deposit storage _d, bool _wasFraud) internal { _d.logStartedLiquidation(_wasFraud); uint256 seized = _d.seizeSignerBonds(); address redeemerAddress = _d.redeemerAddress; // Reclaim used state for gas savings _d.redemptionTeardown(); // if we come from the redemption flow we shouldn't go to auction. // Instead give the signer bonds to redeemer if (_d.inRedemption()) { _d.setLiquidated(); _d.enableWithdrawal(redeemerAddress, seized); _d.logLiquidated(); return; } _d.liquidationInitiator = msg.sender; _d.liquidationInitiated = block.timestamp; // Store the timestamp for auction if(_wasFraud){ _d.setFraudLiquidationInProgress(); } else{ _d.setLiquidationInProgress(); } } /// @notice Anyone can provide a signature that was not requested to prove fraud. /// @dev Calls out to the keep to verify if there was fraud. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. function provideECDSAFraudProof( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { require( !_d.inFunding(), "Use provideFundingECDSAFraudProof instead" ); require( !_d.inSignerLiquidation(), "Signer liquidation already in progress" ); require(!_d.inEndState(), "Contract has halted"); submitSignatureFraud(_d, _v, _r, _s, _signedDigest, _preimage); startLiquidation(_d, true); } /// @notice Closes an auction and purchases the signer bonds. Payout to buyer, funder, then signers if not fraud. /// @dev For interface, reading auctionValue will give a past value. the current is better. /// @param _d Deposit storage pointer. function purchaseSignerBondsAtAuction(DepositUtils.Deposit storage _d) public { bool _wasFraud = _d.inFraudLiquidationInProgress(); require(_d.inSignerLiquidation(), "No active auction"); _d.setLiquidated(); _d.logLiquidated(); // send the TBTC to the TDT holder. If the TDT holder is the Vending Machine, burn it to maintain the peg. address tdtHolder = _d.depositOwner(); uint256 lotSizeTbtc = _d.lotSizeTbtc(); require(_d.tbtcToken.balanceOf(msg.sender) >= lotSizeTbtc, "Not enough TBTC to cover outstanding debt"); if(tdtHolder == _d.vendingMachineAddress){ _d.tbtcToken.burnFrom(msg.sender, lotSizeTbtc); // burn minimal amount to cover size } else{ _d.tbtcToken.transferFrom(msg.sender, tdtHolder, lotSizeTbtc); } // Distribute funds to auction buyer uint256 valueToDistribute = _d.auctionValue(); _d.enableWithdrawal(msg.sender, valueToDistribute); // Send any TBTC left to the Fee Rebate Token holder _d.distributeFeeRebate(); // For fraud, pay remainder to the liquidation initiator. // For non-fraud, split 50-50 between initiator and signers. if the transfer amount is 1, // division will yield a 0 value which causes a revert; instead, // we simply ignore such a tiny amount and leave some wei dust in escrow uint256 contractEthBalance = address(this).balance; address payable initiator = _d.liquidationInitiator; if (initiator == address(0)){ initiator = address(0xdead); } if (contractEthBalance > valueToDistribute + 1) { uint256 remainingUnallocated = contractEthBalance.sub(valueToDistribute); if (_wasFraud) { _d.enableWithdrawal(initiator, remainingUnallocated); } else { // There will always be a liquidation initiator. uint256 split = remainingUnallocated.div(2); _d.pushFundsToKeepGroup(split); _d.enableWithdrawal(initiator, remainingUnallocated.sub(split)); } } } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @param _d Deposit storage pointer. function notifyCourtesyCall(DepositUtils.Deposit storage _d) public { require(_d.inActive(), "Can only courtesy call from active state"); require(getCollateralizationPercentage(_d) < _d.undercollateralizedThresholdPercent, "Signers have sufficient collateral"); _d.courtesyCallInitiated = block.timestamp; _d.setCourtesyCall(); _d.logCourtesyCalled(); } /// @notice Goes from courtesy call to active. /// @dev Only callable if collateral is sufficient and the deposit is not expiring. /// @param _d Deposit storage pointer. function exitCourtesyCall(DepositUtils.Deposit storage _d) public { require(_d.inCourtesyCall(), "Not currently in courtesy call"); require(getCollateralizationPercentage(_d) >= _d.undercollateralizedThresholdPercent, "Deposit is still undercollateralized"); _d.setActive(); _d.logExitedCourtesyCall(); } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @param _d Deposit storage pointer. function notifyUndercollateralizedLiquidation(DepositUtils.Deposit storage _d) public { require(_d.inRedeemableState(), "Deposit not in active or courtesy call"); require(getCollateralizationPercentage(_d) < _d.severelyUndercollateralizedThresholdPercent, "Deposit has sufficient collateral"); startLiquidation(_d, false); } /// @notice Notifies the contract that the courtesy period has elapsed. /// @dev This is treated as an abort, rather than fraud. /// @param _d Deposit storage pointer. function notifyCourtesyTimeout(DepositUtils.Deposit storage _d) public { require(_d.inCourtesyCall(), "Not in a courtesy call period"); require(block.timestamp >= _d.courtesyCallInitiated.add(TBTCConstants.getCourtesyCallTimeout()), "Courtesy period has not elapsed"); startLiquidation(_d, false); } }
Notify the contract that the signers are undercollateralized. Calls out to the system for oracle info. _d Deposit storage pointer.
function notifyUndercollateralizedLiquidation(DepositUtils.Deposit storage _d) public { require(_d.inRedeemableState(), "Deposit not in active or courtesy call"); require(getCollateralizationPercentage(_d) < _d.severelyUndercollateralizedThresholdPercent, "Deposit has sufficient collateral"); startLiquidation(_d, false); }
1,082,841
./full_match/137/0xE869a0D3C1B3B66EBf889b025d13980c39eC5646/sources/project_/contracts/market/ERC721Bids.sol
See {IERC721Bids-numTokenWithBidsOfCollection}./
function numTokenWithBidsOfCollection( address erc721Address ) public view returns (uint256) { return _erc721Bids[erc721Address].tokenIds.length(); }
4,773,906
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; //Simple notary contract to save strings and be able to check later contract NotaryOffice { //Actuall mapping of notarized strings which will be saved on blockchain mapping(bytes32 => bool) private docs; //Setting the owner of the contract address private officeOwner; constructor() public { //Setting the contract owner on deployment officeOwner = msg.sender; } // ----- Events ----- event Document_Stored(string doc, address docOwner); event Document_Checked(string doc, address docChecker); // ----- Modifiers ----- modifier onlyOwner() { require( msg.sender == officeOwner, "Notary Office:Only owner can checkout" ); _; } //Helper function to cast string to bytes and keccak256 hash byte data function hashDoc(string memory _docToHash) private pure returns (bytes32) { return keccak256(bytes(_docToHash)); } // Private function to saved hash data to actuall mapping function storHashInDocs(bytes32 _documentHash) private { docs[_documentHash] = true; } // ----------- Exposed functions ---------------- // Public function to expose saving string ability function storeDoc(string memory _docToSave) public payable { // require 1 ether to save a string require( msg.value >= 1 ether, "Notary Office: We require 1 ether to save a document" ); emit Document_Stored(_docToSave, msg.sender); storHashInDocs(hashDoc(_docToSave)); } // Public function to check for string if it has been saved function checkDocument(string memory _docToCheck) public payable returns (bool) { // require minimum 1 ether for each time checking to be paid require( msg.value >= 1 ether, "Notary Office: We require one ether for our services" ); emit Document_Checked(_docToCheck, msg.sender); return docs[hashDoc(_docToCheck)]; } //checkout public function to get ether back to owner function checkout() public onlyOwner { require( address(this).balance > 1, "Notary Office:We still havent make that much money" ); //Setting amount to balance - 1 to already have some balance uint256 balance = address(this).balance - 1; msg.sender.transfer(balance); } }
Public function to check for string if it has been saved require minimum 1 ether for each time checking to be paid
function checkDocument(string memory _docToCheck) public payable returns (bool) { require( msg.value >= 1 ether, "Notary Office: We require one ether for our services" ); emit Document_Checked(_docToCheck, msg.sender); return docs[hashDoc(_docToCheck)]; }
7,243,401
pragma solidity 0.5.2; import 'openzeppelin-solidity/contracts/lifecycle/Pausable.sol'; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; contract Splitter is Pausable { using SafeMath for uint256; mapping (address => uint) public funds; constructor() public { } event LogFundsAdded ( address indexed sender, uint value, address indexed requester1, address indexed requester2 ); event LogWithdrawnFunds ( address indexed requester, uint indexed value ); // modifier fundsNotZero (address add) { // require(funds[add] > 0, "Address has no funds available to withdraw"); // _; // } function split(address receiver1, address receiver2) payable public whenNotPaused { require(receiver1 != address(0), "Receiving address cannot be zero"); require(receiver2 != address(0), "Receiving address cannot be zero"); require(msg.value>0, "Amount splitted cannot be zero"); uint half = msg.value / 2; funds[receiver1] = funds[receiver1].add(half); //emit LogFundsAdded(receiver1, half); funds[receiver2] = funds[receiver2].add(half); //emit LogFundsAdded(receiver2, half); //uint mod = msg.value %2; funds[msg.sender] = funds[msg.sender].add(msg.value %2); emit LogFundsAdded(msg.sender, msg.value, receiver1, receiver2); } function withdrawFunds() public whenNotPaused { uint amount = funds[msg.sender]; require(amount > 0, "Address has no funds available to withdraw"); funds[msg.sender] = 0; emit LogWithdrawnFunds(msg.sender, amount); msg.sender.transfer(amount); } }
emit LogFundsAdded(receiver1, half);emit LogFundsAdded(receiver2, half);uint mod = msg.value %2;
function split(address receiver1, address receiver2) payable public whenNotPaused { require(receiver1 != address(0), "Receiving address cannot be zero"); require(receiver2 != address(0), "Receiving address cannot be zero"); require(msg.value>0, "Amount splitted cannot be zero"); uint half = msg.value / 2; funds[receiver1] = funds[receiver1].add(half); funds[receiver2] = funds[receiver2].add(half); funds[msg.sender] = funds[msg.sender].add(msg.value %2); emit LogFundsAdded(msg.sender, msg.value, receiver1, receiver2); }
911,415
./partial_match/56/0x8B881A877a650c0F12e806e88575c40E0026C4Be/sources/MasterChef.sol
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.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 viceReward = multiplier.mul(vicePerBlock).mul(pool.allocPoint).div(totalAllocPoint); if((vice.totalSupply() + viceReward.div(10).mul(11)) < 17000000 ether) { vice.mint(devaddr, viceReward.div(10)); vice.mint(address(this), viceReward); } pool.accVicePerShare = pool.accVicePerShare.add(viceReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
11,058,595
pragma solidity ^0.4.24; // File: contracts/LandBasic.sol /** * @title Land interface */ contract LandBasic { function createAndTransfer(address _to, uint32 _world, int64 _x, int64 _y) public; event Create(uint32 indexed _world, int64 indexed _x, int64 indexed _y); } // File: contracts/BidLandBasic.sol /** * @title BidLand interface */ contract BidLandBasic is LandBasic { function setBidPrice(uint32 _worldId, int64 _x, int64 _y, uint256 _biddingPrice) public; function setInfo(uint32 _worldId, int64 _x, int64 _y, string _name, string _description) public; } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/LandPlotAuction.sol /** * @title Block42 Landpot auction * @author Richard Fu ([email protected]) * @dev A auction for bidding plots and create ERC721 land on bidding completed. */ contract LandPlotAuction is Pausable { using SafeMath for uint256; // Represents an auction of a land struct Auction { int64 x; int64 y; uint64 endingTime; // Uses uint64 for saving space Plot[] plots; } // Represents a plot bidding in an auction struct Plot { uint8 x; uint8 y; address bidder; uint8 team; uint256 currentBid; uint256 maxBid; mapping(address => uint256) bids; // Keep track of all bids for final rewards } struct Team { uint8 winnerPortion; uint8 othersPortion; } event Bid(uint8 x, uint8 y, address indexed oldBidder, address indexed bidder, uint8 team, uint256 currentBid); event Refund(uint8 x, uint8 y, address indexed bidder, uint256 weiAmount); event Reward(address indexed bidder, uint256 bidderReward); event Withdraw(address indexed payee, uint256 weiAmount); uint8 constant PLOT_WIDTH = 7; // 7x6 plots uint8 constant PLOT_HEIGHT = 6; uint8 constant PLOT_COUNT = 42; // Cache for better performance and less gas. 7x6 plots = 42 // The current world of all selling lands, this is only change after the final free-trade period uint32 public currentWorldId; // The final jackpot in ETH uint256 public jackpot; // The outbid balance all address, used for people withdraw mapping(address => uint256) public balances; uint256 public totalBalance; // Current auction Auction public currentAuction; // Past auctions mapping(uint32 => Auction[]) public pastAuctions; // WorldId => Auction array mapping(uint256 => Auction) public landAuction; // LandId (ERC721 token) => Auction // Teams Team[] private teams_; // Contract of the ERC721 BidLand BidLandBasic internal bidLandContract_; constructor(address _bidLandAddress) public { bidLandContract_ = BidLandBasic(_bidLandAddress); teams_.push(Team(40, 20)); teams_.push(Team(30, 30)); teams_.push(Team(20, 40)); teams_.push(Team(10, 50)); } /** * @dev fallback function reeiveing ether. */ function() external payable { } /** * @dev Starts a new auction for a new land, contract owner only. */ function startAuction(int64 _x, int64 _y) public onlyOwner { require(currentAuction.endingTime < now, "Current auction not yet ended."); if (currentAuction.x != 0 || currentAuction.y != 0) // Archiving the currect auction pastAuctions[currentWorldId].push(currentAuction); currentAuction.x = _x; currentAuction.y = _y; currentAuction.endingTime = uint64((now - now % 86400) + 1 weeks); bool push = false; if (currentAuction.plots.length == 0) push = true; for (uint8 k = 0; k < PLOT_COUNT; k++) { (uint8 x, uint8 y) = plotIndexToPosition(k); if (push) currentAuction.plots.push(Plot(x, y, address(0), 0, 0, 0)); // Creates new struct and adds it in storage else currentAuction.plots[k] = Plot(x, y, address(0), 0, 0, 0); // Updates the new struct and updates it in storage } } /** * @dev Starts the free-trade period. */ function startFreeTrade() external onlyOwner { startAuction(0, 0); // (0,0) is not for sale so used it as an indicator for free-trade period // TODO } /** * @dev Ends the timer of the current auction manually, used for testing only. */ function endAuction() external onlyOwner { currentAuction.endingTime = uint64(now); } /** * @dev Finalizes the current auction and rewards the land to winner, after the auction ended. */ function finalizeAuction(address winner, uint8 team) external onlyOwner { require(currentAuction.endingTime <= now, "Current auction not yet ended."); require(team > 0 && team <= teams_.length, "Invalid team number."); uint256 totalBid = 0; address[] memory otherWinners = new address[](PLOT_COUNT); uint8 totalOtherWinners = 0; // Run through all plots to get the total rewards for (uint8 k = 0; k < PLOT_COUNT; k++) { Plot storage plot = currentAuction.plots[k]; totalBid = totalBid.add(plot.currentBid); if (plot.team == team && plot.bidder != winner) { // Keeps track of all other winners otherWinners[k] = plot.bidder; totalOtherWinners++; } // Returns the extra bids to all bidders uint256 refund = plot.maxBid.sub(plot.currentBid); balances[plot.bidder] = balances[plot.bidder].add(refund); emitRefund(k, plot.bidder, refund); // Avoid stack too deep error } // Reward winner and others Team storage t = teams_[team - 1]; uint256 winnerReward = totalBid.mul(t.winnerPortion).div(100); rewardWinner(winner, winnerReward); uint256 otherReward = totalBid.mul(t.othersPortion).div(100).div(totalOtherWinners); for (k = 0; k < PLOT_COUNT; k++) { if (otherWinners[k] != address(0)) rewardWinner(otherWinners[k], otherReward); } // Add the rest to jackpot jackpot = jackpot.add(totalBid.mul(100 - t.winnerPortion - t.othersPortion).div(100)); // Creates and Rewards the land for winner bidLandContract_.createAndTransfer(winner, currentWorldId, currentAuction.x, currentAuction.y); bidLandContract_.setBidPrice(currentWorldId, currentAuction.x, currentAuction.y, totalBid); } /** * @dev Emits the Refund event, only for avoiding stack too deep error. */ function emitRefund(uint8 _index, address _bidder, uint256 _weiAmount) internal { if (_bidder != address(0) && _weiAmount > 0) { (uint8 x, uint8 y) = plotIndexToPosition(_index); emit Refund(x, y, _bidder, _weiAmount); } } /** * @dev Rewards the winner and emits event. */ function rewardWinner(address _winner, uint256 _reward) internal { balances[_winner] = balances[_winner].add(_reward); emit Reward(_winner, _reward); } /** * @dev Restarts the whole game with new world ID. World ID must be created with World contract first. */ function restartGame(uint32 _worldId, int64 x, int64 y) external onlyOwner { require(currentAuction.endingTime < now, "Current auction not yet ended."); currentWorldId = _worldId; startAuction(x, y); // TODO } /** * @dev Maps a 2D plot position to a 1D array index. (-3,-3)->(3,3) to 0->49 */ function plotPositionToIndex(uint8 _x, uint8 _y) public pure returns (uint8) { require(_x > 0 && _x <= PLOT_WIDTH, "Invalid x."); require(_y > 0 && _y <= PLOT_HEIGHT, "Invalid y."); return (_x - 1) * PLOT_WIDTH + _y - 1; } /** * @dev Converts a a 1D plot array index to 2D position. 0->49 to (-3,-3)->(3,3) */ function plotIndexToPosition(uint8 _index) public pure returns (uint8, uint8) { require(_index >= 0 && _index <= PLOT_COUNT, "Invalid index."); return (_index / PLOT_WIDTH + 1, _index % PLOT_WIDTH + 1); } /** * @dev Gets info current auction, for testing only. */ function getAuction() external view returns (int64, int64, uint64) { return (currentAuction.x, currentAuction.y, currentAuction.endingTime); } /** * @dev Gets ending time in current auction. */ function getEndingTime() external view returns (uint64) { return currentAuction.endingTime; } /** * @dev Gets a specific plot in current auction. */ function getPlot(uint8 _x, uint8 _y) external view returns (uint8 x, uint8 y, address bidder, uint8 team, uint256 currentBid) { return getPlotByIndex(plotPositionToIndex(_x, _y)); } function getPlotByIndex(uint8 _index) public view returns (uint8 x, uint8 y, address bidder, uint8 team, uint256 currentBid) { Plot storage plot = currentAuction.plots[_index]; return(plot.x, plot.y, plot.bidder, plot.team, plot.currentBid); } /** * @dev Gets all plots in current auction. */ function getPlots() external view returns (uint8[] xs, uint8[] ys, address[] bidders, uint8[] teams, uint256[] currentBids) { xs = new uint8[](PLOT_COUNT); ys = new uint8[](PLOT_COUNT); bidders = new address[](PLOT_COUNT); teams = new uint8[](PLOT_COUNT); currentBids = new uint256[](PLOT_COUNT); for (uint8 k = 0; k < PLOT_COUNT; k++) { Plot storage plot = currentAuction.plots[k]; xs[k] = plot.x; ys[k] = plot.y; bidders[k] = plot.bidder; teams[k] = plot.team; currentBids[k] = plot.currentBid; } } /** * Sets the team portions, used by owner for balancing. */ function setTeamPortions(uint8 team, uint8 winnerPortion, uint8 othersPortion) external onlyOwner { teams_[team].winnerPortion = winnerPortion; teams_[team].othersPortion = othersPortion; } /** * @dev Throws if auctioning land is (0,0), i.e. bidding closed. */ modifier canBid() { require(currentAuction.x != 0 || currentAuction.y != 0, "Invalid plot position."); _; } /** * @dev Bids on a plot by anyone. */ function bid(uint8 _x, uint8 _y, uint8 _team, uint256 _newMaxBid) external payable whenNotPaused canBid { uint8 index = plotPositionToIndex(_x, _y); Plot storage plot = currentAuction.plots[index]; require(_newMaxBid >= plot.currentBid.add(1 finney), "Mix bid must be at least 1 finney more than the current bid."); // Must larger than current bid by at least 1 finney require(_newMaxBid <= msg.value.add(balances[msg.sender]), "Max bid must be less than sending plus available fund."); if (msg.value < _newMaxBid) // Take some ethers from balance subBalance(msg.sender, _newMaxBid.sub(msg.value)); if (_newMaxBid <= plot.maxBid) { // Failed to outbid current bidding, less than its max bid addBalance(msg.sender, _newMaxBid); // Add the current bid to balance, so the bidder can withdraw/reuse later plot.currentBid = _newMaxBid; // Increase the current bid emit Bid(plot.x, plot.y, msg.sender, plot.bidder, plot.team, _newMaxBid); } else { uint256 newCurrentBid = plot.maxBid; if (plot.maxBid == 0) newCurrentBid = 1 finney; // New bid start from 1 finney emit Bid(plot.x, plot.y, plot.bidder, msg.sender, _team, newCurrentBid); if (plot.bidder != address(0)) // Add the bid of the old bidder to balance, so he can withdraw/reuse later addBalance(plot.bidder, plot.maxBid); emptyMyBalance(); // No more balance plot.bidder = msg.sender; plot.team = _team; plot.currentBid = newCurrentBid; plot.maxBid = _newMaxBid; } } /** * @dev Subtracts some wei the balance of an address. */ function subBalance(address _taker, uint _weiAmount) internal { require(balances[_taker] >= _weiAmount, "Not enough balance to subtract."); totalBalance = totalBalance.sub(_weiAmount); balances[_taker] = balances[_taker].sub(_weiAmount); } /** * @dev Adds some wei to the balance of an address. */ function addBalance(address _giver, uint _weiAmount) internal { totalBalance = totalBalance.add(_weiAmount); balances[_giver] = balances[_giver].add(_weiAmount); } /** * @dev Gets all contributed bids at all plots of the current auction. */ function getContributedBids(address _bidder) external view returns (uint8[] xs, uint8[] ys, uint256[] bids) { xs = new uint8[](PLOT_COUNT); ys = new uint8[](PLOT_COUNT); bids = new uint256[](PLOT_COUNT); for (uint8 k = 0; k < PLOT_COUNT; k++) { Plot storage p = currentAuction.plots[k]; if (p.bids[_bidder] > 0) { xs[k] = p.x; ys[k] = p.y; bids[k] = p.bids[_bidder]; } } } /** * @dev Gets the max bid of sender at specfic plot. */ function getMaxBid(uint8 _x, uint8 _y) external view returns (uint256) { Plot storage plot = currentAuction.plots[plotPositionToIndex(_x, _y)]; require(plot.bidder == msg.sender, "Only current bidder can get the max bid."); // Only bidder can get the max bid return plot.maxBid; } /** * @dev Withdraws all remaining outbid balance of sender. */ function withdraw() external { require(balances[msg.sender] > 0, "No balance to withdraw."); uint256 weiAmount = balances[msg.sender]; emptyMyBalance(); msg.sender.transfer(weiAmount); emit Withdraw(msg.sender, weiAmount); } /** * @dev Empties the balance of sender, internal use only. */ function emptyMyBalance() internal { if (balances[msg.sender] > 0) { // Skip if no balance, for saving gas totalBalance = totalBalance.sub(balances[msg.sender]); balances[msg.sender] = 0; } } /** * @dev Gets the earned ETH while keeping enough for jackpot and outbid balances, owner only. */ function getEarning() external view onlyOwner returns (uint256) { return address(this).balance.sub(jackpot).sub(totalBalance); } /** * @dev Deposits ETH into jackpot, for testing and increase final rewards, owner only. */ function depositJackpot() external payable { jackpot = jackpot.add(msg.value); } /** * @dev Withdraws the earned ETH while keeping enough for jackpot and outbid balances, owner only. */ function withdrawEarning() external onlyOwner { require(address(this).balance > jackpot.add(totalBalance), "Not enough balance to withdraw."); msg.sender.transfer(address(this).balance.sub(jackpot).sub(totalBalance)); } /** * @dev Withdraws the all ETH for testing ONLY, owner only. */ function withdrawAll() external onlyOwner { msg.sender.transfer(address(this).balance); } }
Gets all plots in current auction./
function getPlots() external view returns (uint8[] xs, uint8[] ys, address[] bidders, uint8[] teams, uint256[] currentBids) { xs = new uint8[](PLOT_COUNT); ys = new uint8[](PLOT_COUNT); bidders = new address[](PLOT_COUNT); teams = new uint8[](PLOT_COUNT); currentBids = new uint256[](PLOT_COUNT); for (uint8 k = 0; k < PLOT_COUNT; k++) { Plot storage plot = currentAuction.plots[k]; xs[k] = plot.x; ys[k] = plot.y; bidders[k] = plot.bidder; teams[k] = plot.team; currentBids[k] = plot.currentBid; } }
15,833,393
./full_match/5/0x5a08edfCC269505A42fd594F7a00288E4E40BF4b/sources/lib/ERC721B/contracts/extensions/ERC721BBurnable.sol
Burns `tokenId`. See {ERC721B-_burn}. Requirements: - The caller must own `tokenId` or be an approved operator./ Clear approvalsthis is the situation when _owners are normalizedthis is the situation when _owners are not normalized
function burn(uint256 tokenId) public virtual { address owner = ERC721B.ownerOf(tokenId); if (!_isApprovedOrOwner(_msgSender(), tokenId, owner)) revert InvalidCall(); _beforeTokenTransfers(owner, address(0), tokenId, 1); _approve(address(0), tokenId, owner); unchecked { _balances[owner] -= 1; _burned[tokenId] = true; _owners[tokenId] = address(0); _totalBurned++; uint256 nextTokenId = tokenId + 1; if (nextTokenId <= totalSupply() && _owners[nextTokenId] == address(0)) { _owners[nextTokenId] = owner; } } _afterTokenTransfers(owner, address(0), tokenId, 1); emit Transfer(owner, address(0), tokenId); }
1,867,372